如何在Ruby on Rails中使用FactoryGirl创建具有嵌套属性的测试对象?

时间:2013-03-04 13:48:40

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

我的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

2 个答案:

答案 0 :(得分:5)

这是一个堆栈答案,当我试图找出它时,我收藏了一些书签:

factory-girl-nested-factory

编辑:对不起,刚刚意识到答案是纯粹的FactoryGirl而没有rspec。

答案 1 :(得分:1)

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

有关于has_many-associations的部分内容。基本上它所说的是扩展您的发票工厂,并在创建发票后添加一些项目。