2016-02-01 61 views
1

當我運行rspec我得到這個錯誤:如何解決rspec的「未定義的方法`validate_presence_of」錯誤

Failures: 

    1) User 
    Failure/Error: it { should validate_presence_of :email } 

    NoMethodError: 
     undefined method `validate_presence_of' for <RSpec::ExampleGroups::User:0x007f8177ff3408> 
    # ./spec/models/user_spec.rb:5:in `block (2 levels) in <top (required)>' 

Finished in 0.00168 seconds (files took 2.72 seconds to load) 
1 example, 1 failure 

Failed examples: 

rspec ./spec/models/user_spec.rb:5 # User 

但是,如何才能解決這個問題?

這是我的Gemfile:

group :development, :test do 
gem 'byebug' 
gem 'rspec-rails', '~> 3.4', '>= 3.4.1' 
gem "factory_girl_rails", "~> 4.0" 
gem 'capybara', '~> 2.6', '>= 2.6.2' 
# Call 'byebug' anywhere in the code to stop execution and get a  debugger console 
gem 'byebug' 
end 

group :test do 
    gem 'shoulda-matchers', require: false 
end 

這是我的模型:

class User < ActiveRecord::Base 
    validates :email, presence: true 
end 

而且我user_spec:

require 'rails_helper' 

RSpec.describe User, type: :model do 
    #pending "add some examples to (or delete) #{__FILE__}" 
    it { should validate_presence_of :email } 

end 
+0

[可能是幫助](https://github.com/thoughtbot/shoulda/issues/203) – potashin

+0

對於RSpec :: ExampleGroups:[undefined method \'validate \ _presence \ _of' :User :: Validations](http://stackoverflow.com/questions/31276625/undefined-method-validate-presence-of-for-rspecexamplegroupsuservalidati) – Phiter

+2

歡迎來到Stack Overflow。我建議閱讀http://catb.org/esr/faqs/smart-questions.html。它充滿了你的偉大提示。沒有必要說「請幫助我」,因爲這是該網站的用途。我們期待寫得很好的問題,而不是乞討。請花時間格式化您的問題並使用適當的大寫字母;那些回報。 –

回答

1

添加到您的rails_helper.rb

require 'shoulda/matchers' 

您的規格缺少shoulda matcher的方法。

請看看thread。希望這可以幫助

+1

謝謝單加在shoulda_matchers_helper.rb這個:Shoulda :: Matchers.configure do | config | config.integrate do | with | with.test_framework:rspec with.library:rails end end – Rul

相關問題