应该使用class_name和foreign_key来使用belongs_to

Lan*_*opp 18 rspec ruby-on-rails shoulda

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

describe Dog dog
  it { should belong_to(:owner) }
end
Run Code Online (Sandbox Code Playgroud)

是否可以使用Shoulda测试更复杂的belongs_to关系?像这样的东西:

class Dog < ActiveRecord::Base
  belongs_to :owner, :class_name => "Person", :foreign_key => "person_id"
end
Run Code Online (Sandbox Code Playgroud)

geo*_*ock 24

你应该可以使用:

it { should belong_to(:owner).class_name('Person') }
Run Code Online (Sandbox Code Playgroud)

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

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


小智 8

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

it { should belong_to(:owner).class_name('Person').with_foreign_key('person_id') }
Run Code Online (Sandbox Code Playgroud)

请参阅:https://github.com/thoughtbot/shoulda-matchers/blob/master/lib/shoulda/matchers/active_record/association_matcher.rb#L122