【问题标题】:How do I mock an "unless" method for rails using minitest?如何使用 minitest 模拟 Rails 的“除非”方法?
【发布时间】: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


【解决方案1】:

看来您在块内对mc.mymethod 的函数调用正在返回模拟对象,该对象未赋予实际mymethod 函数的功能。这就是这个例子here 所表明的。

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

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

【讨论】:

  • 这一行puts h.third_method # #&lt;Minitest::Mock:0x0000561d744d4030&gt; 表明您要求 h.third_method 返回模拟对象。这就是h.stub :third_method, mock do 所做的。
  • 如果我不调用它,那么 third_method 永远不会被调用。查看修改
猜你喜欢
  • 1970-01-01
  • 2012-05-14
  • 1970-01-01
  • 2012-07-29
  • 1970-01-01
  • 2012-02-09
  • 1970-01-01
  • 1970-01-01
  • 2020-02-18
相关资源
最近更新 更多