Shoulda_matches错误:#RSpec的未定义方法`validate_presence_of':: ExampleGroups :: Idea_3 :: Validations :: Title:0x007f3f88fa7548>

Man*_*dyM 2 ruby unit-testing rspec ruby-on-rails shoulda

我正在学习TDD并尝试使用shoulda_matchers来帮助我进行测试,但是我得到了一个非常奇怪的错误.这是我的测试:

规格/型号/ idea_spec.rb

require 'rails_helper'

describe Idea do

  context 'Validations' do
    describe 'title' do
       it { should validate_presence_of(:title) }
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

测试错误说:

Idea Validations title 
 Failure/Error: it { should validate_presence_of(:title) }
 NoMethodError:
   undefined method `validate_presence_of' for #<RSpec::ExampleGroups::Idea_3::Validations::Title:0x007f056f9fcdf8>
 # ./spec/models/idea_spec.rb:7:in `block (4 levels) in <top (required)>'
Run Code Online (Sandbox Code Playgroud)

根据gem指令,require' Shoulda/matchers'位于我的rails_helper文件的顶部.

宝石我正在使用:

group :development, :test do
  gem 'spring'
  gem 'dotenv-rails'
  gem 'rspec-rails', '~> 3.0'
  gem 'factory_girl_rails'
end

group :test do
  gem 'webmock', '~> 1.20.4'
  gem 'shoulda-matchers', require: false
end
Run Code Online (Sandbox Code Playgroud)
  1. 红宝石'2.1.2'
  2. rails','4.1.9'

Uzz*_*zar 12

Shoulda-Matchers不再自动安装到您的测试框架中.您需要将其添加到rails_helper:

Shoulda::Matchers.configure do |config|
  config.integrate do |with|
    with.test_framework :rspec
    with.library :rails
  end
end
Run Code Online (Sandbox Code Playgroud)

请参阅此GitHub问题,阅读有关shoulda-matchers配置的说明,并阅读维护者发布的这篇博客文章.


tpb*_*den 5

require: false在你的Gemfile中,这意味着在运行测试时没有加载匹配器.在rails_helper.rb你需要require 'shoulda/matchers'在顶部添加行.