ruby-on-rails - 无法在 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...end
intest_helper.rb
会导致第一个错误?我无法从实际代码库中删除该代码,那么如何修改它以使用它mocha
?
红宝石版本:2.4.1
导轨版本:4.2.8
摩卡版本:1.5.0
解决方案
在工程super
中的修补方法中添加调用:before_setup
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
# do something
super
end
end
此调用super
允许调用before_setup
of Mocha::Integration::MiniTest
,这是正确初始化所必需的。
推荐阅读
- python - Binance api 保证金错误:'code': 200003900 'msg': ... 试图从受限司法管辖区访问我们的服务
- c# - C#调用接口方法在许多类中实现,而没有这些类的实例
- python - 使用 Python 从 Web 下载文件时出错
- flutter - Json AppBar 使用
- java - equals() 和 hashCode() 可以是 lambdas 吗?
- python - 贝叶斯网络边缘的置信度
- python - 是否在可能之前将 asyncio 库应用于书面库?
- laravel - 如何使用 vue axios 请求访问会话?
- django - DoesNotExist:匹配的查询不存在
- android - 如何实现 Facebook 服务之类的东西