【发布时间】:2020-02-23 04:09:51
【问题描述】:
我有一些代码试图模拟“myerror”场景:
class Hello < ApplicationRecord
def first_method
[{:myid=>1}, {:myid=>2}]
end
def second_method
puts self.first_method
return nil unless self.first_method
self.first_method.first
end
def third_method
puts self.second_method.nil? # true
raise "myerror" unless self.second_method
puts self.second_method.nil? # true
self.second_method[:myid]
end
end
为了确保发生错误,我需要将“first_method”设置为 nil,并且在我的测试中(使用 minitest)我有:
require 'test_helper'
class HelloTest < ActiveSupport::TestCase
test '#hello_is_normal' do
h = hellos(:one)
h.first_method
h.second_method
h.third_method
end
test '#hello_example_should_fail' do
mock = Minitest::Mock.new
mock.expect :first_method, nil
mock.expect :second_method, nil
mock.expect :nil?, true
mock.expect :nil?, true
h = hellos(:one)
h.stub :second_method, mock do
puts h.third_method
end
结束 结束
但它似乎不起作用,因为 third_method 不会导致 'myerror' 被引发。
【问题讨论】:
-
您的测试中的语法是否正确?
-
应该是
mock.expect :something, nil吧?为什么不在mymethod中放一个断点,看看发生了什么? -
@lacostenycoder:你的意思是倒数第二行?不,那绝对是
SyntaxError。 -
哦。对不起这个不好的例子。我已经对其进行了更新,以使其(希望)更清晰。
-
unless是关键字,而不是方法。这意味着“除非方法”只是胡言乱语。只需创建一个不太抽象的示例来演示您实际尝试解决的问题。
标签: ruby-on-rails ruby