Jak*_*ake 5 ruby-on-rails factory-bot
我的位置工厂中有以下内容:
FactoryBot.define do
factory :location do
name 'MyString'
hours_operation 'MyString'
abbreviation 'MyString'
address_1 'MyString'
address_2 'MyString'
city 'MyString'
state 'MyString'
postal_code 1
phone 'MyString'
fax 'MyString'
association :region
end
end
Run Code Online (Sandbox Code Playgroud)
我的地区工厂有以下内容:
FactoryBot.define do
factory :region do
name 'MyString'
end
end
Run Code Online (Sandbox Code Playgroud)
Region has_many location 和 Locations Beings_to region。
但是在我的测试中,我不断收到验证失败:区域必须存在。
我尝试了以下方法:
after(:create) do |location, _evaluator|
create_list(:region, evaluator.region, location: location)
end
association :region, factory: region
before(:create) do |region|
region.location << FactoryBot.build(:location, region: region)
end
Run Code Online (Sandbox Code Playgroud)
我也试过在地区工厂:
factory :region_with_location do
after(:create) do |region|
create(:location, region: region)
end
end
Run Code Online (Sandbox Code Playgroud)
在地点工厂:
association :region, factory: :region_with_location
Run Code Online (Sandbox Code Playgroud)
在每种情况下,我仍然不断收到:验证失败:区域必须存在。
小智 1
由于Locationbelongs_to ,在构建和保存LocationRegion之前必须在测试数据库中创建Region的实例。这就是为什么你的代码在这里不起作用,正如 @Niklas 所说:
after(:create) do |location, _evaluator|
create_list(:region, evaluator.region, location: location)
end
Run Code Online (Sandbox Code Playgroud)
您可以做相反的事情:创建区域后通过关联构建位置列表。
FactoryGirl.define do
factory :region do
name 'MyString'
factory :region_with_locations do
transient do
locations_count 5
end
after(:create) do |region, evaluator|
create_list(:location, evaluator.locations_count, region: region)
end
end
end
Run Code Online (Sandbox Code Playgroud)
您还可以考虑使用before(:create)回调来创建区域,然后再将其分配给位置。
| 归档时间: |
|
| 查看次数: |
7466 次 |
| 最近记录: |