应该用class_name和foreign_key来表示belongs_to



我知道您可以使用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_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

相关内容

最新更新