【问题标题】:Applying FactoryGirl trait to Mongoid embedded objects将 FactoryGirl 特征应用于 Mongoid 嵌入对象
【发布时间】:2013-02-20 14:41:02
【问题描述】:

我正在使用 Mongoid 构建 Rails 3.2.11 应用程序。我用 Cucumber 测试并用 FactoryGirl 创建测试对象。我有嵌入的对象。我希望能够将 FactoryGirl 特征与我的父对象和嵌入对象一起使用,以进行大量排列并保持干燥。

问题:我似乎无法将特征应用于嵌入对象。

model.rb(实际上是单独的模型文件)

class User    
   include Mongoid::Document

   #Fields and stuff
   embeds_one :car
end

class Car    
   include Mongoid::Document

   #Fields and stuff
   embedded_in :user 
end

spec/factories.rb

FactoryGirl.define do
  factory :user do

    status 'active'     # shared attribute  

    trait :bob do
     name 'Bob'
     email 'bob@bob.com'
    end

    trait :carol do
     name 'Carol'
     email 'carol@carol.com'
    end

    car  { [FactoryGirl.build(:car)] }

  end

  factory :car do

    number_of_tires 4   # shared attribute

    trait :red_ford do
     make 'Ford'
     color 'Red'
    end

    trait :blue_chevy do
     make 'Chevy'
     color 'Blue'
    end

  end
end

features/step_definitions/user_steps.rb(无法正常工作)

Given /^There is a user Bob with a Blue Chevy$/ do
  FactoryGirl.create(:user, :bob, :car => [:car => :blue_chevy])
end

如果我不使用嵌入式对象特征,我可以工厂创建用户对象。有什么方法可以使用所需的特征来构建嵌入式对象?谢谢!

修复

Thoughtbot 的 Joshua Clayton http://joshuaclayton.me 说:

没有将特征应用于关联的简写语法; 基本上,你必须这样做:

cars = [FactoryGirl.build(:car, :blue_chevy)]
FactoryGirl.create(:user, :bob, cars: cars)

【问题讨论】:

    标签: ruby-on-rails-3 mongoid factory-bot


    【解决方案1】:

    因为是1对1的关系,所以在spec/factories.rb中构建汽车对象时不需要数组

    car { FactoryGirl.build(:car) }

    这也适用于黄瓜步骤。另外,据我了解,特征用作属性,因此您的步骤代码应如下所示

    FactoryGirl.create(:user, :bob, :car, :blue_chevy)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-06-10
      • 2013-04-29
      • 2014-07-25
      • 1970-01-01
      • 1970-01-01
      • 2013-10-31
      • 1970-01-01
      相关资源
      最近更新 更多