2011-03-19 34 views
1

我不明白與rspec的測試關聯(has_many/belongs_to)相當基本的內容。儘管用戶無效(has_many/belongs_to關聯),Rspec - respond_to「user post」仍然有效

協會型號:

user has_many :posts 
post belongs_to :user 

我設置沒有任何屬性和測試的用戶,如果一個職位應的respond_to用戶。該測試是有效的,但用戶無效(而不是創建)。

我知道respond_to只通過關聯測試帖子的存在,但是如果沒有有效的用戶,它如何存在呢?有人可以解釋我爲什麼嗎?謝謝!

user_spec.rb

require 'spec_helper' 

describe User do 

    describe "post associations" 

    before(:each) do 
     @user = User.create(@attr) #no attribute is set 
    end 

    it "should have a post attribute" do 
     @user.should respond_to(:posts) 
    end 

    end 

end 

回答

2

用戶確實回覆帖子,它只是返回一個空數組。在Rails控制檯試試這個:

> @user = User.new 
> @user.posts 
=> [] 

一個更好的檢驗可能是:

@user.posts.should be_empty 

老實說測試軌道的關係通常不建議你基本上測試軌道它的自我這已經是非常行之有效的。

然而,早該提供了一些很好的匹配,在rspec的工作,以檢查關係設置正確:

it {should have_many(:posts)} 

檢查它在github上:https://github.com/thoughtbot/shoulda

+0

感謝我試過沒有之前測試( :每個)塊,我得到以下錯誤:失敗/錯誤:@ user.should respond_to(:職位)預計無迴應:職位。給我的理解。我會看看應該。謝謝! – benoitr 2011-03-19 17:29:52

相關問題