【问题标题】:Shoulda matchers have_many with custom relation name匹配器应该有自定义关系名称
【发布时间】:2014-02-09 10:24:39
【问题描述】:

如何使用 should 匹配器测试这个 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) }

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

【问题讨论】:

    标签: ruby-on-rails rspec shoulda


    【解决方案1】:

    应该匹配器包含.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
    

    【讨论】:

    • 准确!我之前尝试过with_foreign_key,但不知道我也必须在User 模型中定义它。我认为 ActiveRecord 会通过阅读 Article 模型来了解它。现在它通过了,非常感谢!
    猜你喜欢
    • 2016-04-19
    • 2017-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多