在FactoryGirl中的find_or_initialize_by [英] find_or_initialize_by in FactoryGirl

查看:106
本文介绍了在FactoryGirl中的find_or_initialize_by的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道FactoryGirl中是否有find_or_initialize_by的等效项可以解决以下问题:

I was wondering if there's an equivalent for find_or_initialize_by in FactoryGirl that solve teh following issue:

目标是该模型使用两个具有相同国家/地区的表格.我不想使用该国家/地区的序列(如我在电子邮件"中所发现的那样).

The objective is that the model uses two tables that have the same country. I don't want to use a sequence for the country (as I found for Emails).

国家/地区"有一个唯一性约束,但是我的主要问题是,当我一次调用FactoryGirl.create(:click)

There's a uniqueness constraint on Country, but my main issue is that it create twice the same record of Country when I call once FactoryGirl.create(:click)

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

Thus, the Validation fail in the test.

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

推荐答案

您应该可以使用initialize_with来完成这项工作:

You should be able to make this work by using initialize_with:

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

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

This will always use the same country. You may want to nest the factory to allow other factories to use different names:

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

这篇关于在FactoryGirl中的find_or_initialize_by的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆