在FactoryGirl中查找_or_initialize_by

问题描述 投票:1回答:2

我想知道FactoryGirl中的find_or_initialize_by是否有相当于解决以下问题:

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

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

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

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
ruby-on-rails rspec factory-bot
2个回答
3
投票

你应该能够通过使用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

0
投票

我遇到了类似的问题,也是我的应用程序的Country模型。这就是我做的。

为了确保FactoryBot的buildcreate仍然能够正常运行,我们应该通过以下方式覆盖to_create的逻辑:

factory :country do
  to_create do |instance|
    instance.attributes = Country.create_with(name: instance.name).find_or_create_by(slug: instance.slug).attributes
    instance.reload
  end

  name { "United States" }
  slug { "us" }
end

查询说明:

Country
.create_with(name: instance.name) # if not found, create with this `name` (and `slug` defined below)
.find_or_create_by(slug: instance.slug) # find by primary key `slug'

这可以确保build维护它“构建/初始化对象”的默认行为,并且不会执行任何数据库读取或写入,因此它总是很快。如果存在,则仅覆盖create的逻辑以获取现有记录,而不是尝试始终创建新记录。

最初发布于https://stackoverflow.com/a/55235861/3956879

看看我的article解释这个。

© www.soinside.com 2019 - 2024. All rights reserved.