我知道您可以使用Shoulda:轻松测试归属关系
describe Dog dog
it { should belong_to(:owner) }
end
是否可以使用Shoulda测试更复杂的归属关系?类似这样的东西:
class Dog < ActiveRecord::Base
belongs_to :owner, :class_name => "Person", :foreign_key => "person_id"
end
您应该能够使用:
it { should belong_to(:owner).class_name('Person') }
Shoulda的belong_to
匹配器总是从关联中读取foreign_key
,并测试它是否是一个有效的字段名,因此您不需要再做任何操作。
(参见Shoulda::Matchers::ActiveRecord::AssociationMatcher#foreign_key_exists?
和相关方法)
现在可以测试自定义外键:
it { should belong_to(:owner).class_name('Person').with_foreign_key('person_id') }
请参阅:https://github.com/thoughtbot/shoulda-matchers/blob/master/lib/shoulda/matchers/active_record/association_matcher.rb#L122
如果关联类似
belongs_to :custom_profile, class_name: 'User', foreign_key: :custom_user_id, optional: true
那么rspec应该是
it { should belong_to(:custom_profile).class_name('User').with_foreign_key('custom_user_id').optional }
这里optional
用于optional:true,如果关联中不需要optional-true,您也可以将其删除
因此,should matchers README对细节非常了解,只是有一些示例。我发现类的RDoc中有更多的信息,在belongs_to
的情况下,看看association_matcher.rb。第一个方法是使用RDoc 进行belongs_to
# 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
的测试。
我知道我参加聚会有点晚了,所以我的解决方案可能需要shoulda
的最新版本。
在写这篇文章的时候,我在v 2.4.0
。
我的规范中不需要class_name
或with_foreign_key
确保在模型中指定了class_name
和foreign_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