应该使用class_name和foreign_key的belongs_to关联方式

24

我知道你可以使用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
5个回答

27

16

4
如果关联类似于
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,则不能省略。

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


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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接