我在想,如果有一个相当于find_or_initialize_by
在解决德以下问题FactoryGirl:
我们的目标是,该模型使用了具有同一个国家的两个表。 我不想使用该国的顺序(因为我发现了电子邮件)。
有一个关于国家唯一性约束,但我的主要问题是,它创建国家两次相同的记录时,我再次呼吁FactoryGirl.create(:点击)
因此,在验证失败的考验。
Rspec的:
# 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