应该使用自定义关系名称匹配器 has_many [英] Shoulda matchers have_many with custom relation name

查看:33
本文介绍了应该使用自定义关系名称匹配器 has_many的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用应该匹配器测试这个 ActiveRecord 关系?

How do I test this ActiveRecord relation using shoulda matchers?

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 因为用户类名称.我希望必须有一些测试方法可以用来覆盖这种期望,如

So it obviously expects relation field to be named user_id because of User class name. I expect there has to be some test method that can be used to override this expectation like

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

但是我找不到类似的东西.我是否遗漏了一些明显的东西?

But I can't find anything like it. Am I missing something obvious?

推荐答案

匹配器应该包含一个 .with_foreign_key() 选项.

shoulda matchers includes a .with_foreign_key() option.

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

所以在你的例子中:

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

我相信您的模型应该如何:

Which is how your model should, I believe:

class User < ActiveRecord::Base
  has_many :articles, foreign_key: "author_id"
end

这篇关于应该使用自定义关系名称匹配器 has_many的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆