2011-08-11 15 views
0

シンプルで何かを試してみて、わかりやすいものを見落としています。 Factory_Girlは自動的に関連付けを作成してはいけませんか?もしそうなら、event_idであり、なので、なぜ "GET index"仕様が失敗するのですか?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でイベントを渡す場合の構文はどうですか? *:第2の仕様の例を参照してください。* – Meltemi

+0

':post => @ attr.merge(:event => Factory.create(:event))'と ':event'キーをマージします新しく作成されたEventオブジェクトへ)を@attrハッシュに追加し、メソッドに渡します。 – MrDanA

+0

ええ、私はちょうどそれをした...しかし、不器用な感じ...しかし、うまく動作します。 thx – Meltemi

0

validates_presence_of :event_id 

を変更してみてくださいFactoryGirlのwikiから0

validates_presence_of :event 
+0

'validates_presence_of:event_id'はまだ問題ありません。 OPは 'validates_associated:event'を追加することができます(このスコープのRailsのバージョンはわかりません)。 – MrDanA

関連する問題