匹配器应该有_many 和自定义关系名称

2024-03-07

如何使用测试此 ActiveRecord 关系shoulda匹配者?

Models

class User < ActiveRecord::Base
  has_many :articles
end

class Article < ActiveRecord::Base
  belongs_to :author, class_name: 'User'
end

Test

describe User do
  it { should have_many(:articles) }
end

我收到以下错误:

1) User should have many articles
     Failure/Error: it { should have_many(:articles) }
       Expected User to have a has_many association called articles (Article does not have a user_id foreign key.)
     # ./spec/models/user_spec.rb:4:in `block (2 levels) in <top (required)>'

所以它显然期望关系字段被命名user_id因为用户类名。我希望必须有一些测试方法可以用来覆盖这个期望,例如

it { should have_many(:articles).as(:owner) }

但我找不到类似的东西。我错过了一些明显的事情吗?


应该匹配器包括一个.with_foreign_key() option.

https://github.com/thoughtbot/shoulda-matchers#have_many https://github.com/thoughtbot/shoulda-matchers#have_many

所以在你的例子中:

describe User do
  it { should have_many(:articles).with_foreign_key('author_id') }
end

我相信你的模型应该是这样的:

class User < ActiveRecord::Base
  has_many :articles, foreign_key: "author_id"
end
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

匹配器应该有_many 和自定义关系名称 的相关文章

随机推荐