gpt4 book ai didi

ruby-on-rails - FactoryGirl 中的 find_or_initialize_by

转载 作者:行者123 更新时间:2023-12-02 17:39:11 25 4
gpt4 key购买 nike

我想知道 FactoryGirl 中是否有与 find_or_initialize_by 等效的方法来解决以下问题:

目标是该模型使用具有相同国家/地区的两个表。我不想为国家使用序列(正如我为电子邮件找到的那样)。

Country 有一个唯一性约束,但我的主要问题是当我调用一次 FactoryGirl.create(:click) 时,它会创建两次相同的 Country 记录

因此,验证在测试中失败。

R规范:

# models/click_spec.rb
describe Click do
it "should have a valid constructor" do
FactoryGirl.create(:click).should be_valid
end
end

工厂:

# factories/countries.rb
FactoryGirl.define do
factory :country do
name "United States"
slug "us"
end
end

# factories/offers.rb
FactoryGirl.define do
factory :offer do
association :country, factory: :country
# Other columns
end
end

# factories/users.rb
FactoryGirl.define do
factory :user do
association :country, factory: :country
# Other columns
end
end

# factories/clicks.rb
FactoryGirl.define do
factory :click do
association :offer, factory: :offer
association :user, factory: :user
# Other columns
end
end

型号:

class Country < ActiveRecord::Base
validates :name, :slug,
presence: true,
uniqueness: { case_sensitive: false }

validates :slug,
length: { is: 2 }

end

最佳答案

你应该能够通过使用 initialize_with 来完成这项工作:

FactoryGirl.define do
factory :country do
name "United States"
slug "us"
initialize_with { Country.find_or_create_by_name(name) }
end
end

这将始终使用同一个国家。您可能希望嵌套工厂以允许其他工厂使用不同的名称:

FactoryGirl.define do
factory :country do
initialize_with { Country.find_or_create_by_name(name) }
factory :united_states do
name "United States"
slug "us"
end
end
end

关于ruby-on-rails - FactoryGirl 中的 find_or_initialize_by,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22874292/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com