未定义的方法`belongs_to'对于RSpec,Rails

时间:2016-12-19 07:11:29

标签: ruby-on-rails ruby rspec

运行rspec测试时,我收到如下错误。

Failure/Error: it { should belong_to :user }

     NoMethodError:
       undefined method `belong_to' for #<RSpec::ExampleGroups::UserEventFavorite:0x007fd0fa9c66c0>

我发现belongs_to特定于Shoulda Matcher。但是,我应该正确安装Shoulda Matcher,如下面的spec_helper.rbrails_helper.rb所示。有人能告诉我这里缺少什么吗?

spec_helper.rb

ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'shoulda/matchers'

RSpec.configure do |config|
  config.expect_with :rspec do |expectations|
    expectations.include_chain_clauses_in_custom_matcher_descriptions = true
  end
  config.mock_with :rspec do |mocks|
    mocks.verify_partial_doubles = true
  end
  config.shared_context_metadata_behavior = :apply_to_host_groups
  config.include RSpec::RequestDescriber, type: :request
  config.before :all do
    FactoryGirl.factories.clear
    FactoryGirl.reload
  end
  config.before :suite do
    DatabaseRewinder.clean_all
  end
  config.after :each do
    DatabaseRewinder.clean
  end
  Autodoc.configuration.toc = true
end

rails_helper.rb

RSpec.configure do |config|
  config.include RSpec::RequestDescriber, type: :request
  # config.include RequestHelpers, type: :request
  # config.include RequestMacros, type: :request

  config.before :all do
    FactoryGirl.factories.clear
    FactoryGirl.find_definitions
    FactoryGirl.reload
  end

  config.before :suite do
    DatabaseRewinder.clean_all
  end

  config.after :each do
    DatabaseRewinder.clean
  end

  Shoulda::Matchers.configure do |config|
    config.integrate do |with|
      with.test_framework :rspec
      with.library :rails
    end
  end
end

这是规范代码:

require 'spec_helper'
require 'rails_helper'
describe UserEventFavorite do
  let(:user_event_favorite) { FactoryGirl.build :user_event_favorite }
  subject { user_event_favorite }

  it { should respond_to :user_id }
  it { should respond_to :event_id }

  it { should belong_to :user }
  it { should belong_to :event }
end

1 个答案:

答案 0 :(得分:3)

我发现了问题。

我需要在我的规范代码中添加type: :model。工作解决方案是:

describe UserEventFavorite, type: :model do
  let(:user_event_favorite) { FactoryGirl.build :user_event_favorite }
  subject { user_event_favorite }

  it { should respond_to :user_id }
  it { should respond_to :event_id }

  it { should belong_to :user }
  it { should belong_to :event }
end

而不是

describe UserEventFavorite do
  let(:user_event_favorite) { FactoryGirl.build :user_event_favorite }
  subject { user_event_favorite }

  it { should respond_to :user_id }
  it { should respond_to :event_id }

  it { should belong_to :user }
  it { should belong_to :event }
end