【问题标题】:How do I test associations in models with RSpec in Rails 5?如何在 Rails 5 中使用 RSpec 测试模型中的关联?
【发布时间】:2016-09-21 08:49:39
【问题描述】:

我是 Rails 5 的新手,正在尝试测试一个极其简单的数据库模型,但我似乎无法做到正确。我正在尝试测试has_many 关联。

模型代码如下:

app/models/database_models/response.rb

module DatabaseModels
  class Response < ApplicationRecord

    has_many :question_responses, :class_name => 'DatabaseModels::
QuestionResponse'

  end
end

规范(RSpec)看起来像这样

spec/models/screener_response_spec.rb

require 'rails_helper'

describe DatabaseModels::Response, type: :model do
  it { is_expected.to have_many(:question_responses) }
end

它失败了:

expected #&lt;DatabaseModels::Response:0x007fd91ccda210&gt; to respond to `has_many?`

我做错了什么?

【问题讨论】:

  • 您是否包含了 shoulda gem?据我所知,只有这个 gem 提供了你正在使用的匹配器。
  • 我的 Gemfile 中的 :test 组中确实有 gem 'shoulda-matchers'
  • 有一个开放的 Rails 5 PR github.com/thoughtbot/shoulda-matchers/pull/960 。我认为这个 gem 还没有准备好 Rails 5。
  • 是否有另一种方法可以在没有shoulda_matchers的情况下使用 RSpec 进行测试
  • expect(described_class.reflect_on_association(:question_responses).macro).to eq :has_many 也应该适用于 Rails 5。

标签: ruby-on-rails rspec ruby-on-rails-5


【解决方案1】:

一种测试方法是测试实际行为:

require 'rails_helper'

describe DatabaseModels::Response, type: :model do

  let(:response) { described_class.new }
  it 'has many question responses' do
    expect( response.question_responses.new ).to be_a_new DatabaseModels::
QuestionResponse 
  end
end

否则你可以使用反射,这基本上是 shoulda 所做的:

require 'rails_helper'

describe DatabaseModels::Response, type: :model do
  it 'has many question responses' do
    relation = described_class.reflect_on_association(:question_resp‌​onses)
    expect(relation.macro).to eq :has_many
  end
end

【讨论】:

  • 不过,我最近在 Rails 5 应用程序中使用了 shoulda-matchers 来测试 has_many 关系,它运行顺利 - 你确定你记得将更改保存在模型文件中吗?跨度>
  • 我确实保存了。也许我的语法有些不对劲,但无法弄清楚。
  • 嗯,如果你这样做 it should have_many(:question_responses).class_name('DatabaseModels::QuestionResponse') 会发生什么?附带说明一下,我相信您可以在此处删除类名选项,因为这两个类具有相同的模块嵌套。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-12
  • 1970-01-01
  • 2017-05-28
  • 1970-01-01
相关资源
最近更新 更多