Ruby on rails Shoulda_matches错误:未定义的方法'validate_presence_of';对于#<;RSpec::ExampleGroups::Idea_3::Validations::Title:0x007f3f8fa7548>;
我正在学习TDD并尝试使用shoulda_匹配器来帮助我进行测试,但我遇到了一个非常奇怪的错误。这是我的测试: 规格/型号/理念\规格rbRuby on rails Shoulda_matches错误:未定义的方法'validate_presence_of';对于#<;RSpec::ExampleGroups::Idea_3::Validations::Title:0x007f3f8fa7548>;,ruby-on-rails,ruby,unit-testing,rspec,shoulda,Ruby On Rails,Ruby,Unit Testing,Rspec,Shoulda,我正在学习TDD并尝试使用shoulda_匹配器来帮助我进行测试,但我遇到了一个非常奇怪的错误。这是我的测试: 规格/型号/理念\规格rb require 'rails_helper' describe Idea do context 'Validations' do describe 'title' do it { should validate_presence_of(:title) } end end end 测试中的错误显示: Idea Val
require 'rails_helper'
describe Idea do
context 'Validations' do
describe 'title' do
it { should validate_presence_of(:title) }
end
end
end
测试中的错误显示:
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)>'
GEM文件中的
require:false
表示在运行测试时没有加载匹配程序。在rails\u helper.rb
中,您需要在顶部添加行require'shoulda/matchers'
。如果平台出于某种原因要求您将shoulda matchers
依赖项设置为可选,那么您必须在编写的每个测试的顶部添加require'shoulda/matchers'
但是,如果没有授权,则选择从gempec中删除require:false
。之后:
context 'Validations' do
加
不应该再自动将自己安装到测试框架中。您需要将其添加到rails\u帮助器:
Shoulda::Matchers.configure do |config|
config.integrate do |with|
with.test_framework :rspec
with.library :rails
end
end
请参阅,阅读,然后阅读此内容。我遇到了相同的问题,并通过以下提示解决了此问题:
- 在您的规范中:
require 'rails_helper'
- /rails\u助手
require 'rspec/rails' require 'shoulda/matchers'
- 仍在/rails\u帮助程序中,请不要添加:
Shoulda::Matchers.configure do |config| config.integrate do |with| with.test_framework :rspec with.library :rails end end
- /gemfile
group :development, :test do gem 'shoulda-matchers', '~> 2.5.0', require: false
- 不需要等级库中的宝石助手
config.include(Shoulda::Matchers::ActiveRecord, type: :model)
Shoulda::Matchers.configure do |config|
config.integrate do |with|
with.test_framework :rspec
with.library :rails
end
end
rails_helper.rb
config.include(Shoulda::Matchers::ActiveRecord, type: :model)
Shoulda::Matchers.configure do |config|
config.integrate do |with|
with.test_framework :rspec
with.library :rails
end
end
以下为最新更新: 在你的档案里
group :test do
gem 'shoulda-matchers', '~> 3.0'
end
在rails_helpers.rb的末尾
Shoulda::Matchers.configure do |config|
config.integrate do |with|
# Choose a test framework:
#with.test_framework :minitest
#with.test_framework :minitest_4
#with.test_framework :test_unit
with.test_framework :rspec
# Choose one or more libraries:
with.library :active_record
with.library :active_model
with.library :action_controller
# Or, choose the following (which implies all of the above):
with.library :rails
end
end
谢谢,我已经补充了。希望它有帮助,它解决了你的问题吗?如果是的话,请勾选答案,谢谢。对不起,我在发布问题之前已经添加了答案,现在仍然有问题。谢谢,我已经添加了,因为require:false必须存在。