FactoryGirl名称“不能为空”VS“已经拍摄”

时间:2014-04-04 22:03:31

标签: ruby-on-rails rspec factory-bot

我试图在模型上运行一些测试"点击"。

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

目标是该模型使用两个具有相同国家/地区的表格。我不想为国家使用序列(正如我发现的电子邮件)。 但它引发了这个错误:

Validation failed: Name has already been taken, Slug has already been taken

问题在于它似乎创造了两倍的国家[名称:"美国",slug:"我们"]

这是所使用的工厂。

# 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

我试图将关联策略更改为以下内容:

association :country, factory: :country, strategy: :build

但它引发了这个错误:

Validation failed: Country can't be blank

有什么想法吗?

谢谢,

1 个答案:

答案 0 :(得分:2)

根据共享代码,

致电FactoryGirl.create(:click)

它将执行factory :click,找到association :offer, factory: :offer 反过来调用factory: :offer您首次创建name "United States"slug "us"的国家/地区。

同样,在factory :click中,它会找到association :user, factory: :user,而factory: :user会再次调用name "United States",您可以使用相同的slug "us"和{{1}再次创建国家/地区} 第二次。

  

问题#1:验证失败:名称已被采用,Slug已被采取

上述错误是由于Countrynameslug模型的唯一性限制。

  

问题#2:验证失败:国家/地区不能为空

执行association :country, factory: :country, strategy: :build时,strategy: :build只创建一个Country实例,它会在数据库中创建一条记录。

Country can't be blank错误是因为您没有在数据库中为useroffer创建国家/地区记录。您必须在这两个模型中对presence: truecountry的模式级别检查进行验证not null