【问题标题】:What am I doing wrong in Shoulda Matchers?我在应该匹配器中做错了什么?
【发布时间】:2015-10-28 23:20:53
【问题描述】:

在 gem 文件中我这样写:

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

我的 rails_helper

require 'rspec/rails'
require 'shoulda/matchers'

我的 spec_helper

require 'rails_helper'


RSpec.configure do |config|
  config.expect_with :rspec do |expectations|
    expectations.include_chain_clauses_in_custom_matcher_descriptions = true
  end

  config.include FactoryGirl::Syntax::Methods




  config.mock_with :rspec do |mocks|
    mocks.verify_partial_doubles = true
  end


  Shoulda::Matchers.configure do |config|

    config.integrate do |with|
      # Choose a test framework:
      with.test_framework :rspec

      # Choose one or more libraries:
      with.library :active_record
      with.library :active_model
      with.library :action_controller
    end
  end

最后是我的测试:

require 'spec_helper'
describe Person do

  it {should validate_presence_of(:identifier)}
end

我得到 nomethoderror

     Failure/Error: it {should validate_presence_of(:identifier)}
 NoMethodError:
   undefined method `validate_presence_of' for #<RSpec::ExampleGroups::Person:0x007fe58d13ca20>

我只是不明白。在其他项目中以同样的方式工作。这里没有。我花了两天时间来解决这个问题。 Rails 中是否有更好的 Shoulda Matchers 替代品?

【问题讨论】:

  • 摆脱require: false

标签: ruby-on-rails ruby nomethoderror shoulda


【解决方案1】:

抱歉,您遇到了问题。在需要 shoulda-matchers 之前,您需要加载 Rails。 gem 只会在看到 ActiveRecord 可用时才使模型匹配器可用;如果没有,那么您将无法获得它们。

看来您已经交换了 rails_helper 和 spec_helper。通常在安装了 rspec-rails 的新项目中,rails_helper 将加载 Rails,然后需要 spec_helper。我会删除这两个文件(或将它们移到一边,以便您仍然拥有它们),然后重新运行 rails g rspec:install 以重新生成它们。您仍然希望像之前那样将 shoulda-matchers 配置块添加到 rails_helper,但此时应该加载 ActiveRecord(以及 Rails 的其余部分)。

【讨论】:

    【解决方案2】:

    更改您的 Gemfile 以使用两个不同的组进行测试,如下所示:

    group :test, :development do
      gem 'rspec-rails'
      gem 'factory_girl'
    end
    
    group :test do
      gem 'shoulda-matchers', require: false
    end

    shoulda 加载 Test::Unit 而不是 RSpec 时,会导致 使用,但我认为这已修复。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-14
      • 2011-08-28
      相关资源
      最近更新 更多