繁体   English   中英

如何使用 minitest 模拟 Rails 的“除非”方法?

[英]How do I mock an “unless” method for rails using minitest?

我有一些代码试图模拟“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' 被提升。

看来您在块中对mc.mymethod的 function 调用正在返回模拟 object,它没有给出实际mymethod function 的功能。 这就是这个例子所要说明的。

我不确定你是否真的想要存根这个方法。 也许只需使用 let 语句将something内容设置为nil ,然后在任何存根代码块之外的实际 mc.mymethod 上运行mc.mymethod并对其进行测试。

那应该会产生您期望的异常

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM