与Rails中的FactoryBot / Factory Girl创建关联

时间:2019-11-20 05:26:39

标签: rspec factory-bot

我有三个彼此关联的工厂:Country类具有States类,而States具有City类。

countries.rb

FactoryBot.define do
factory :country do
    name { Faker::Address.unique.country }
  end
end

states.rb

FactoryBot.define do
factory :state do
    association :country
    name { Faker::Address.state }
  end
end

cities.rb

   FactoryBot.define do
    factory :city do
        association :state
        name { Faker::Address.city }
      end
    end

在我的规范中,我想实例化特定的对象。

  before(:each) do
    create(:city, name:"Buffalo")
    create(:state, name:"New York")
    create(:country, name:"United States")

  end

我如何将美国和纽约州,布法罗联系起来?

1 个答案:

答案 0 :(得分:1)

您可以将每个对象作为另一个工厂的属性来传递。

before(:each) do
  country = create(:country, name:"United States")
  state = create(:state, name:"New York", country: country)
  create(:city, name:"Buffalo", state: state)
end

但是,这使您无法访问这些测试对象。而是对每个对象使用let!

let!(:country) { create(:country, name:"United States") }
let!(:state) { create(:state, name:"New York", country: country) }
let!(:city) { create(:city, name:"Buffalo", state: state) }

现在,您可以在示例中参考countrystatecity。除非特别需要为测试创建对象,否则可能应该使用let并允许按需创建它们。

最后,我们可以通过反转来节省大量工作。创建城市,然后从城市中检索州,并从州中检索国家。

let(:city) { create(:city) }
let(:state) { city.state }
let(:country) { state.country }

您可以在测试中引用city.name,而不用指定确切的名称。例如。

let(:city) { create(:city) }
let(:state) { city.state }
let(:country) { state.country }

describe '#find_city' do
  it 'finds a city by name' do
    expect( country.find_city(city.name) ).to eq city
  end
end

describe '#find_state' do
  it 'finds a state by name' do
    expect( country.find_state(state.name) ).to eq state
  end
end