ruby-on-rails - NoMethodError:#<RSpec::ExampleGroups::CompetitionsController::Create> 的未定义方法 `mock'

标签 ruby-on-rails ruby unit-testing ruby-on-rails-4 rspec

Variants这个问题已被多次问到,但大多数都与摩卡有关,而我没有使用它。我是 Rails 的新手,所以这看起来微不足道,但我无法在我的规范文件中使用 mock(用于名为 competitions 的 Controller )。

  require 'rails_helper'
  require 'spec_helper'

  describe CompetitionsController do
    before :each do
      @fake_c = mock(Competition, :competition_id => 1, :competition_name => 'one', :competition_des => 'any')
    end
    describe 'create' do
      it 'should create new competition' do
        #CompetitionsController.stub(:create).and_return(mock('Competition'))
        #post :create, {:id=>"1"}
      end
    end
  end

我只停留在 mock 方法上,所以我没有写太多其他内容。 我的 spec_helper 文件包含以下内容

ENV["RAILS_ENV"] ||= 'test'
require 'simplecov'
SimpleCov.start
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'rspec/autorun'

RSpec.configure do |config|
  # rspec-expectations config goes here. You can use an alternate
  # assertion/expectation library such as wrong or the stdlib/minitest
  # assertions if you prefer.
  config.expect_with :rspec do |expectations|
    # This option will default to `true` in RSpec 4. It makes the `description`
    # and `failure_message` of custom matchers include text for helper methods
    # defined using `chain`, e.g.:
    #     be_bigger_than(2).and_smaller_than(4).description
    #     # => "be bigger than 2 and smaller than 4"
    # ...rather than:
    #     # => "be bigger than 2"
    expectations.include_chain_clauses_in_custom_matcher_descriptions = true
  end

  # rspec-mocks config goes here. You can use an alternate test double
  # library (such as bogus or mocha) by changing the `mock_with` option here.
  config.mock_with :rspec do |mocks|
    # Prevents you from mocking or stubbing a method that does not exist on
    # a real object. This is generally recommended, and will default to
    # `true` in RSpec 4.
    mocks.verify_partial_doubles = true
  end
end

我正在使用 ruby​​ 版本 2.2.1 和 rails 4.2.1

最佳答案

使用 double 而不是 mock,这应该可以解决您的问题:

before :each do
  @fake_c = double('Competition', :competition_id => 1, :competition_name => 'one', :competition_des => 'any')
end

关于ruby-on-rails - NoMethodError:#<RSpec::ExampleGroups::CompetitionsController::Create> 的未定义方法 `mock',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33182271/

相关文章:

unit-testing - 单元测试和这样做的动机

ruby-on-rails - Rails 3.1 和 Heroku - 即使使用 'therubyracer-heroku' 仍然无法工作

ruby-on-rails - Paperclip 在 Rails 中将图像上传到 S3。文件上传速度非常慢。解决方法?

javascript - Ruby 中的非阻塞定时事件,如 JavaScript setTimeout

unit-testing - 使用 PageObjects 测试具有嵌套在内部的复杂角度组件的组件

unit-testing - 单元测试 Redux Sagas

ruby-on-rails - Rails Under Construction 页面

ruby-on-rails - 将 Id 数组从 View 传回 Rails Controller

ruby-on-rails - 如何识别 RSpec Controller 规范中调用的路由

ruby-on-rails - 如何找到数组中最大值的位置?