应该使用class_name 和foreign_key [英] Shoulda belongs_to with class_name and foreign_key
本文介绍了应该使用class_name 和foreign_key的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道您可以使用 Shoulda 轻松测试归属关系:
describe Dog dog它{应该属于(:所有者)}结尾
是否可以使用 Shoulda 测试更复杂的belongs_to 关系?像这样:
class Dog "人", :foreign_key =>person_id"结尾
解决方案
您应该能够使用:
它{应该属于(:owner).class_name('Person') }
Shoulda 的 belong_to
匹配器总是从关联中读取 foreign_key
并测试它是否是有效的字段名称,因此您无需再执行任何操作.>
I know you can easily test a belongs to relationship using Shoulda:
describe Dog dog
it { should belong_to(:owner) }
end
Is it possible to test a more complicated belongs_to relationship using Shoulda? Something like this:
class Dog < ActiveRecord::Base
belongs_to :owner, :class_name => "Person", :foreign_key => "person_id"
end
解决方案
You should be able to use:
it { should belong_to(:owner).class_name('Person') }
Shoulda's belong_to
matcher always reads the foreign_key
from the association and tests that it is a valid field name, so you don't need to do anything more.
(See Shoulda::Matchers::ActiveRecord::AssociationMatcher#foreign_key_exists?
and associated methods)
这篇关于应该使用class_name 和foreign_key的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文