应该使用class_name和foreign_key来使用belongs_to

时间:2012-09-02 08:15:30

标签: ruby-on-rails rspec shoulda

我知道您可以使用Shoulda轻松测试属于该关系:

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

5 个答案:

答案 0 :(得分:24)

你应该可以使用:

it { should belong_to(:owner).class_name('Person') }

Shoulda的belong_to匹配器总是从关联中读取foreign_key并测试它是否是有效的字段名称,因此您不需要再做任何其他事情。

(参见Shoulda::Matchers::ActiveRecord::AssociationMatcher#foreign_key_exists?及相关方法)

答案 1 :(得分:7)

现在可以测试自定义外键:

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

答案 2 :(得分: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

答案 3 :(得分:2)

所以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的测试。

答案 4 :(得分:1)

如果关联类似于

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用于可选:true,如果您的关联中不需要true,也可以将其删除

相关问题