2011-08-11 2 views
0

간단하고 간단한 것을 간과하면 확실합니다. Factory_Girl이 자동으로 연결을 생성하면 안됩니까? 그렇다면 event_id이 아니기 때문에 "GET 인덱스"사양이 실패한 이유는 무엇입니까??Factory_girl을 통한 연관성 검사에서 RSpec 검증에 실패했습니다.

이벤트 has_many : 게시물

#post.rb 
    ... 
    belongs_to :event 
    validates :event_id, :presence => true 
    ... 

#factories.rb 
Factory.define :event do |event| 
    event.name "The Long Event Title" 
end 

Factory.define :post do |post| 
    post.title "This is a post" 
    post.association :event 
end 


#posts_controller_spec.rb 
before(:each) do 
    @attr = Factory.attributes_for(:post) 
end 

describe "GET index" do 
    it "assigns all posts as @posts" do 
    post = @user.posts.create(@attr) ### <-- event_id not assigned? 
    # post = FactoryGirl.create(:post) ### <-- this doesn't work either 
    get :index 
    assigns(:posts).should eq([post]) 
    end 
end 

편집 : 추가 사양 예 :

describe "POST create" do 
    describe "with valid params" do 
     it "creates a new Post" do 
     expect { 
      post :create, :post => @attr, :event => Factory.create(:event) <- fail 
     }.to change(Post, :count).by(1) 
     end 

답변

1

: https://github.com/thoughtbot/factory_girl/wiki/Usage

 
# Attribute hash (ignores associations) 
user_attributes = Factory.attributes_for(:user) 

그래서 당신이 EVENT_ID을받지 못하고 있으며, 그것이 실패 왜 그건.

또한 post = FactoryGirl.create(:post)을 시도했지만 post = Factory.create(:post)을 실행하면 제대로 작동합니다.

아마 before() 블록에서 게시물을 만들고 저장해야합니다. 아직 저장하지 않으려는 테스트가 없다면 말입니다.

+0

@attr과 함께 이벤트를 전달하려는 경우 구문은 무엇입니까? * 위의 두번째 스펙 예제를 참조하십시오. * – Meltemi

+0

다음과 같이 할 수 있습니다 :': post => @ attr.merge (: event => Factory.create (: event))'그러면': event' 키에 병합됩니다. 새로 생성 된 Event 객체에)를 @attr 해시에 추가 한 다음 메서드에 전달합니다. – MrDanA

+0

그래, 방금 했어 ... 서투른 느낌이 들지만 ... 괜찮아. thx – Meltemi

0

변화 시도

validates_presence_of :event_id 

에 FactoryGirl 위키에서 0
validates_presence_of :event 
+0

'validates_presence_of : event_id'는 여전히 괜찮습니다. OP는'validates_associated : event'를 추가 할 수 있습니다 (어느 범위의 Rails 버전이 유효한지 모르겠습니다). – MrDanA