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

Tin*_*n81 14 rspec ruby-on-rails rspec2 ruby-on-rails-3 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
Run Code Online (Sandbox Code Playgroud)

我试图使用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
Run Code Online (Sandbox Code Playgroud)

不幸的是,此测试(以及所有其他测试)失败并显示来自RSpec的此错误消息:

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

如何创建包含可通过测试的项目的发票?

我正在使用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
Run Code Online (Sandbox Code Playgroud)

小智 5

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

工厂女孩嵌套厂

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