2017-02-14 3 views
2

컨트롤러와 모델을 테스트하기위한 테스트를 만들고 있습니다. FactoryGirl을 사용하여 가짜 데이터를 생성 할 때 사용자가 (레코드가 속한) 오류가 발생합니다. 여기 RSpec 오류 사용자가 FactoryGirl과 함께 존재해야합니다.

여기
class Composition < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :group 

    validates :name, presence: true, uniqueness: {scope: :user_id} 

end 

이 내가 여기까지

require 'rails_helper' 

    describe CompositionsController do 

    before(:each) do 
     @user = FactoryGirl.create(:user) 
     @group = FactoryGirl.create(:group) 
     sign_in @user 
     @composition = Composition.new(FactoryGirl.create(:composition), user_id: @user.id, group_id: @group.id) 
    end 

    describe "GET #index" do 
    it "renders the index template" do 
     get :index 

     expect(assigns(:composition).to eq(@composition)) 
     expect(response).to render_template("index") 
    end 
    end 

end 
까지가 내 RSpec에 테스트 내 FactoryGirl 파일 composition.rb

require 'faker' 

FactoryGirl.define do 
    factory :composition do 
    name { Faker::Name.name } 
    description { Faker::Lorem.words } 
    import_composition { Faker::Boolean.boolean } 
    import_composition_file { Faker::File.file_name('path/to') } 
    end 
end 

내 모델 composition.rb입니다

지금 바로 오류가 발생합니다 : 유효성 검사 실패 : 사용자가 존재해야합니다. G 지붕이 존재해야합니다

FactoryGirl을 사용하여 레코드를 만들지 않았 으면 모든 것이 잘 작동합니다.

신체에 문제가있는 이유에 대한 제안이 있습니까? 당신이 레코드를 생성하고 싶지만 그냥 초기화 대신 build를 사용하지 않을 경우

+0

'''@composition = FactoryGirl.create (: composition, user_id : @ user.id, group_id : @ group.id)''' – cutalion

답변

0

당신은

@composition = FactoryGirl.create(:composition, user: @user, group: @group) 

을 모델에 PARAM로 FactoryGirl을 통과 할 필요가 없습니다 create

@composition = FactoryGirl.build(:composition, user: @user, group: @group) 
+0

고마워! 이 문제가 해결되었습니다. 지금 실행 중입니다. 모든 테스트가 통과되었습니다. – Samuel