【问题标题】:How to state FactoryGirl fixtures for associated model data?如何为关联模型数据声明 FactoryGirl 夹具?
【发布时间】:2011-09-19 23:02:20
【问题描述】:

我正在使用 Ruby on Rails 3.0.9、RSpec-rails 2 和 FactoryGirl。我想生成一些与用户帐户相关的工厂关联模型数据(在User 类中,我声明了has_one :account 关联),以便在规范文件中执行以下操作:

let(:user) { Factory(:user) } 

it "should have an account" do
  user.account.should_not be_nil # Note: 'user.account'
end

此时我有一个factories/user.rb 文件,如下所示:

FactoryGirl.define do
  factory :user, :class => User do |user|
    user.attribute_1
    user.attribute_2
    ...
  end
end

还有一个factories/users/account.rb 文件,如下所示:

FactoryGirl.define do
  factory :users_account, :class => Users::Account do |account|
    account.attribute_1
    account.attribute_2
    ...
  end
end

为了处理规范文件中的 RoR 相关模型,说明 FactoryGirl 数据的正确\常用方式是什么?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 rspec rspec2


    【解决方案1】:

    首先,您不需要 :class=> 用户,因为它会自动推断。

    FactoryGirl.define do
      factory :user do
        attribute_1      'Some'
        attribute_2      'Text'
      end
    end
    

    要在您的工厂中使用关联,只需直接包含名称即可:

    FactoryGirl.define do
      factory :post do
        user
        title    'Hello'
        body     'World'
      end
    end
    

    在上面的示例中,用户将与帖子相关联。

    你也可以使用命名工厂:

    FactoryGirl.define do
      factory :post do
        association :user, :factory => :administrator
        title    'Hello'
        body     'World'
      end
    end
    

    documentation 解释了一切。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多