Minitest为JSON:Module

时间:2019-04-16 19:33:28

标签: ruby-on-rails mocking ruby-on-rails-5 minitest stub

我一直在使用Mocha和minitest在Rails5中完成一些工作,包括自定义类和Net / *。但是,我现在正尝试引发JSON :: ParserError,并且得到了NoMethodError: undefined method 'any_instance' for JSON:Module

require 'json'
require 'mocha/mini_test'
JSON.any_instance.stubs(:parse).raises(JSON::ParserError)

我尝试过https://github.com/freerange/mocha/issues/218,但是没有用。不知道导致这些问题的JSON可能有什么不同。还尝试仅使用存根和do块。

更新:

代码如下:

begin
  parsed_json = JSON.parse(raw_json)
rescue JSON::ParserError
  puts 'Exception Caught in Code'  # <-- This line prints in the test console.
end

这是测试代码:

test 'should fail because json error' do
  JSON.stubs(:parse).raises(JSON::ParserError)
end

这会导致在测试should fail because json error中引发异常,但未提及源代码。如果我在测试中添加了急救措施,它也会被抓住:

test 'should fail because json error' do
  JSON.stubs(:parse).raises(JSON::ParserError)
rescue JSON::ParserError
  puts 'Exception Caught in Test'  # <-- This line prints in the test console too.
end

0 个答案:

没有答案
相关问题