首页 > 解决方案 > 无法在 ruby​​ on rails 测试中使用 mocha 存根

问题描述

我对 Ruby/Ruby on Rails 还很陌生,并且mocha在通过现有代码库中存根方法时遇到了麻烦。

我已将代码简化为 MWE,它会在此中断。

这里是test_helper.rb

ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)

require "rails/test_help"


class ActiveSupport::TestCase

end


class Minitest::Test
  def before_setup

  end
end

这是测试:

require 'test_helper'
require 'mocha/minitest'

class MyTest < ActionMailer::TestCase

  describe "some test" do
    it "should stub" do
      My::Class.stubs(:bar).returns("foo")
      puts My::Class.bar
    end
  end

end

当我运行测试时,这会导致以下错误:

Mocha::NotInitializedError: Mocha methods cannot be used outside the context of a test

但是,当我重新定义我test_helper.rb的如下:

ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)

require "rails/test_help"


class ActiveSupport::TestCase

end


# class Minitest::Test
#   def before_setup
#
#   end
# end

测试通过(并且“foo”按预期打印)。

为什么class Minitest::Test...endintest_helper.rb会导致第一个错误?我无法从实际代码库中删除该代码,那么如何修改它以使用它mocha

红宝石版本:2.4.1

导轨版本:4.2.8

摩卡版本:1.5.0

标签: ruby-on-railsrubyruby-mocha

解决方案


在工程super中的修补方法中添加调用:before_setuptest_helper.rb

ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)

require "rails/test_help"


class ActiveSupport::TestCase

end


class Minitest::Test
  def before_setup
      # do something
      super
  end
end

此调用super允许调用before_setupof Mocha::Integration::MiniTest,这是正确初始化所必需的。


推荐阅读