ruby-on-rails - 应该使用自定义关系名称匹配器 has_many

标签 ruby-on-rails rspec 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_id因为用户类名。我希望必须有一些测试方法可以用来覆盖这个期望,比如
it { should have_many(:articles).as(:owner) }

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

最佳答案

应该是匹配器包括一个 .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

关于ruby-on-rails - 应该使用自定义关系名称匹配器 has_many,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21657906/

相关文章:

ruby-on-rails - Ruby haml 意外结束错误

ruby-on-rails - 尝试测试嵌套属性时 Rspec 抛出的未知属性错误

ruby - Autotest、Shoulda、Ruby - 设置?

ruby-on-rails - 应该从战壕中测试工作流程

ruby-on-rails - 工厂女孩什么时候在数据库中创建对象?

ruby-on-rails - rails - 找不到生成器 rspec :install.

javascript - 在 ruby​​ on Rails 4 中完成项目

ruby-on-rails - Rails-仅当另一个字段具有特定值时,才如何验证一个字段?

ruby - 如果有条件,Rails 4 模型 rspec

ruby - RSpec:如何编写一个期望特定输出但不关心方法的测试?