使用Rspec測試失敗

[英]Test with Rspec let is failing


I have problem with FactoryGirl and RSpec. I have following test:

我有FactoryGirl和RSpec的問題。我有以下測試:

require 'rails_helper'
describe Customer do
  it_behaves_like "Account"

  describe "it has an address" do
    let(:customer) {create(:customer)}
    let(:address) {create(:address, addressable_id: customer.id, addressable_type: "Account")}

    it "should have an address" do
      expect(customer.address).to eq address
    end
  end
end

When I try to run it throws me following error:

當我嘗試運行它時會拋出以下錯誤:

) Customer it has an address should have an address
     Failure/Error: expect(customer.address).to eq address

       expected: #<Address id: 1, street: "Street 1", zip_code: "11-111", city: "City 1", addressable_id: 1, addressable_type: "Account", created_at: "2014-09-26 10:07:51", updated_at: "2014-09-26 10:07:51">
            got: nil

       (compared using ==)
     # ./spec/models/customer_spec.rb:11:in `block (3 levels) in <top (required)>'

But when I refactor it to something like this:

但是當我將它重構為這樣的東西時:

require 'rails_helper'

describe Customer do
  it_behaves_like "Account"

  describe "it has an address" do
    before do
      @customer = create(:customer)
      @address = create(:address, addressable_id: @customer.id, addressable_type: "Account")
    end

    it "should have an address" do
      expect(@customer.address).to eq @address
    end
  end
end

It works properly. Why my example with let is failing?

它工作正常。為什么我的let例子失敗了?

1 个解决方案

#1


3  

That's because let is evaluated lazily.

那是因為懶惰地評估了let。

Calling expect(customer.address) invokes your first let block, i.e. create(:customer) . It returns a customer without an address.

調用expect(customer.address)調用您的第一個let塊,即create(:customer)。它返回沒有地址的客戶。

The second let block create(:address, ...) is not invoked until calling eq address.

第二個let塊create(:address,...)在調用eq地址之前不會被調用。

You can use let! to create the address instantly:

你可以用let!立即創建地址:

let!(:address) { create(:address, ...) }

Another option is to use a custom factory customer_with_address that sets the association.

另一種選擇是使用自定義工廠customer_with_address來設置關聯。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2014/09/26/ba0e41148db28691f7af92497ee54149.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com