我知道你可以使用Shoulda轻松测试belongs to关系:
describe Dog dog
it { should belong_to(:owner) }
end
使用Shoulda能否测试更复杂的belongs_to关系?比如这样:
class Dog < ActiveRecord::Base
belongs_to :owner, :class_name => "Person", :foreign_key => "person_id"
end
我知道你可以使用Shoulda轻松测试belongs to关系:
describe Dog dog
it { should belong_to(:owner) }
end
使用Shoulda能否测试更复杂的belongs_to关系?比如这样:
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') }
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,则不能省略。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