2013-03-04 26 views
13

Tôi có một mô hình Invoice có thể chứa một số Items cũng như:Làm thế nào để tạo các đối tượng thử nghiệm với các thuộc tính lồng nhau với FactoryGirl trong Ruby on Rails?

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 

Tôi cố gắng để kiểm tra điều này bằng 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 

Thật không may, thử nghiệm này (và tất cả những người khác) thất bại với thông báo lỗi này từ RSpec:

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

Làm cách nào để tạo hóa đơn với các mục sẽ vượt qua bài kiểm tra?

Tôi đang sử dụng FactoryGirl để chế tạo đồ vật như thế này:

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 

Trả lời

4

Đây là một câu trả lời chồng tôi đánh dấu khi tôi đã cố gắng tìm nó ra:

factory-girl-nested-factory

Edit: Xin lỗi, chỉ nhận ra câu trả lời là PureGirl thuần túy và không có rspec.

+0

OK, cảm ơn nhưng tôi không thể làm cho nó hoạt động theo cách đó. – Tintin81

Các vấn đề liên quan