应该匹配自定义关系名称的匹配器

时间:2014-02-09 10:24:39

标签: ruby-on-rails rspec shoulda

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

模型

class User < ActiveRecord::Base
  has_many :articles
end

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

测试

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类名,显然希望关系字段被命名为user_id。我希望必须有一些测试方法可以用来覆盖这种期望,如

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

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

1 个答案:

答案 0 :(得分:9)

shoulda matchers包含.with_foreign_key()选项。

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