2012-09-02 84 views
17

我知道你可以輕鬆地測試一個屬於使用早該到關係:早該belongs_to的與CLASS_NAME和foreign_key

describe Dog dog 
    it { should belong_to(:owner) } 
end 

是否有可能測試使用早該更復雜的belongs_to的關係?事情是這樣的:

class Dog < ActiveRecord::Base 
    belongs_to :owner, :class_name => "Person", :foreign_key => "person_id" 
end 

回答

2

所以should-matchers自述是在細節上很輕,只是有一些例子。我發現在類的RDoc中有很多信息,在belongs_to的情況下請看association_matcher.rb。第一種方法是belongs_to的與RDOC

# Ensure that the belongs_to relationship exists. 
    # 
    # Options: 
    # * <tt>:class_name</tt> - tests that the association makes use of the class_name option. 
    # * <tt>:validate</tt> - tests that the association makes use of the validate 
    # option. 
    # 
    # Example: 
    # it { should belong_to(:parent) } 
    # 
    def belong_to(name) 

所以belongs_to:class_name:validate唯一支持的測試。

3

我知道我有點遲到了,所以我的解決方案可能需要最新版本shoulda。我寫在v 2.4.0

我並不需要class_namewith_foreign_key在我的規範。

確保在模型中指定了class_nameforeign_key

# model.rb: 
belongs_to :owner, inverse_of: :properties, class_name: "User", foreign_key: :owner_id 

# spec.rb: 
it { should belong_to(:owner) } 

得到的輸出:

should belong to owner 
相關問題