FactoryGirl创建不完整的模型 [英] FactoryGirl creates incomplete model

查看:92
本文介绍了FactoryGirl创建不完整的模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个城市模型,其中:

Assume that I have a city model where:

class city
  field :full_name, type: String # San Francisco, CA, United States
  field :_id, type: String, overwrite: true, default: ->{ full_name }
end

假设我在/spec/factories/cities.rb 中定义了一个工厂:

Assume that I have a factory defined in /spec/factories/cities.rb:

FactoryGirl.define do
  factory :city do
    full_name 'San Francisco, CA, United States'
  end
end

在其中一个规范中运行以下代码:

Running the following code in one of the specs:

city_attrs = { full_name: 'San Francisco, CA, United States' }
City.create! city_attrs
=> #<City _id: San Francisco, CA, United States, full_name: "San Francisco, CA, United States">

FactoryGirl.create(:city)
=> #<City _id: , full_name: "San Francisco, CA, United States">

如何解决此问题而不在/spec/factories/cities.rb 中添加以下代码?

How do I fix this without adding the following code to the /spec/factories/cities.rb?

before(:create) do |city, evaluator|
  city.id = city.full_name
end

编辑 解决方案是停止使用FactoryGirl并使用 Fabrication 代替

EDIT the solution is to stop using FactoryGirl and use Fabrication instead as recommended in this answer

推荐答案

您需要覆盖FactoryGirl使用的模型的初始化:

You need to override the initialization of the model used by FactoryGirl:

FactoryGirl.define do
  trait :explicit_initialize do
    initialize_with { new(attributes) }
  end

  factory :city, traits: [:explicit_initialize] do
    full_name 'San Francisco, CA, United States'
  end

end

这篇关于FactoryGirl创建不完整的模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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