シンプルで何かを試してみて、わかりやすいものを見落としています。 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
@attrでイベントを渡す場合の構文はどうですか? *:第2の仕様の例を参照してください。* – Meltemi
':post => @ attr.merge(:event => Factory.create(:event))'と ':event'キーをマージします新しく作成されたEventオブジェクトへ)を@attrハッシュに追加し、メソッドに渡します。 – MrDanA
ええ、私はちょうどそれをした...しかし、不器用な感じ...しかし、うまく動作します。 thx – Meltemi