14

私は同様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
4

2 に答える 2

5

これは、理解しようとしていたときにブックマークしたスタックの回答です。

ファクトリー・ガール・ネスト・ファクトリー

編集:申し訳ありませんが、答えが純粋なFactoryGirlであり、rspecがないことに気付きました。

于 2013-03-04T14:54:21.320 に答える
1

https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md#associationsを確認しましたか?

has_many-associations に関する部分があります。基本的には、請求書を作成した後にいくつかのアイテムを追加するもので請求書工場を拡張することです。

于 2013-03-05T20:16:37.820 に答える