【问题标题】:How to create test objects with nested attributes with FactoryGirl in Ruby on Rails?如何在 Ruby on Rails 中使用 FactoryGirl 创建具有嵌套属性的测试对象?
【发布时间】:2013-03-04 13:48:39
【问题描述】:

我有一个Invoice 模型,其中可能还包含多个Items

class Invoice < ActiveRecord::Base

  attr_accessible :number, :date, :recipient, :items_attributes

  belongs_to :user

  has_many :items

  accepts_nested_attributes_for :items, :reject_if => :all_blank, :allow_destroy => true

end

我正在尝试使用 RSpec 进行测试:

describe InvoicesController do

  describe 'user access' do

    before :each do
      @user = FactoryGirl.create(:user)
      @invoice = @user.invoices.create(FactoryGirl.attributes_for(:invoice))
      sign_in(@user)
    end

    it "renders the :show view" do
      get :show
      expect(response).to render_template :show
    end

  end

end

很遗憾,此测试(以及所有其他测试)失败,并显示来自 RSpec 的以下错误消息:

Failure/Error: @invoice = @user.invoices.create(FactoryGirl.attributes_for(:invoice))
ActiveModel::MassAssignmentSecurity::Error:
Can't mass-assign protected attributes: items

如何创建包含通过测试的商品的发票?

我正在使用 FactoryGirl 来制作这样的对象:

factory :invoice do
  number { Random.new.rand(0..1000000) }
  recipient { Faker::Name.name }
  date { Time.now.to_date }
  association :user
  items { |i| [i.association(:item)] } 
end

factory :item do
  date { Time.now.to_date }
  description { Faker::Lorem.sentences(1) }
  price 50
  quantity 2
end

【问题讨论】:

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


    【解决方案1】:

    这是我在试图弄清楚时添加了书签的堆栈答案:

    factory-girl-nested-factory

    编辑:抱歉,刚刚意识到答案是纯 FactoryGirl 而不是 rspec。

    【讨论】:

      【解决方案2】:

      你检查过https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md#associations吗?

      有一部分是关于 has_many-associations 的。基本上它所说的是用一个在创建发票后添加一些项目的发票工厂来扩展你的发票工厂。

      【讨论】:

        猜你喜欢
        • 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
        相关资源
        最近更新 更多