嘗試一些簡單並忽略顯而易見的事情我確信。 Factory_Girl不應該自動創建關聯嗎?如果是這樣,爲什麼「GET索引」規格下面的失敗,因爲event_id
是無?RSpec驗證無法通過Factory_girl進行關聯
事件的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傳遞一個事件,語法是什麼? *參見上面的第二個規範示例* – Meltemi
您可以這樣做:':post => @ attr.merge(:event => Factory.create(:event))'並且它將合併到':event'鍵中到新創建的Event對象)到@attr散列中,然後將它傳遞給您的方法。 – MrDanA
是的,我只是這樣做......雖然......感覺笨拙,但工作正常。 thx – Meltemi