2011-08-11 31 views
0

嘗試一些簡單並忽略顯而易見的事情我確信。 Factory_Girl不應該自動創建關聯嗎?如果是這樣,爲什麼「GET索引」規格下面的失敗,因爲event_idRSpec驗證無法通過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 

回答

1

從FactoryGirl維基:https://github.com/thoughtbot/factory_girl/wiki/Usage

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

這樣你就不會得到一個事項標識,這就是爲什麼它的失敗。

此外,你說你試過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 

validates_presence_of :event 
+0

'validates_presence_of:event_id'仍然沒問題。 OP可能會添加'validates_associated:event'(不知道這個版本的Rails的作用域)。 – MrDanA