用 Ruby-on-Rails 和 MiniTest 存根

Stubbing with Ruby-on-Rails and MiniTest

我正在尝试了解存根如何与 RailsMiniTest 一起使用。我遵循了 MiniTest documentation 中的简单示例。我坚持一个非常简单的例子:

require 'minitest/mock'
require "test_helper"

class TotoTest < ActiveSupport::TestCase

  class Clazz
    def foo
      "foo"
    end
  end

  test "Stubbing" do
    puts Clazz.new.foo # "foo" is well printed
    Clazz.stub :foo, "bar" do # ERROR HERE
      assert_equal "bar", Clazz.new.foo
    end
  end
end

存根时,我收到一个错误提示方法 foo。完整的执行日志:

Testing started at 13:55 ...
[...]
Started

foo

Minitest::UnexpectedError: NameError: undefined method `foo' for class `TotoTest::Clazz'
    test/models/toto_test.rb:14:in `block in <class:TotoTest>'
test/models/toto_test.rb:14:in `block in <class:TotoTest>'
Finished in 0.52883s
1 tests, 0 assertions, 0 failures, 1 errors, 0 skips

Process finished with exit code 0

我开始不明白为什么我被告知 foo 方法不存在,而前一行的执行运行良好。

我错过了什么?为什么这不起作用?

我什至尝试过另一种方法,使用模拟:

require 'minitest/mock'
require "test_helper"

class TotoTest < ActiveSupport::TestCase

  class Clazz
    def foo
      "foo"
    end
  end

  test "Stubbing" do
    mock = Minitest::Mock.new
    def mock.foo
      "bar"
    end

    puts Clazz.new.foo
    Clazz.stub :foo, mock do
      assert_equal "bar", Clazz.new.foo
    end
  end
end

结果是一样的。我哪里错了?

编辑:用例

更准确地说,我想存根 YouTube API。对 YouTube API 的调用是在一个模块中实现的。该模块包含在控制器中。在系统测试中,我想用存根替换对该 API 的真实调用,以独立于 YouTube API。

您正在存根 class 方法而不是实例方法:

Clazz.stub :foo, "bar"

您在常量 Clazz.

引用的 Class class 实例上调用 stub

您应该在 Clazz 个实例上调用 #stub

clazz = Clazz.new
clazz.stub :foo, mock do
  assert_equal "bar", clazz.foo
end

编辑: 关于用例。我认为控制器不适合包含处理外部 API 的方法。我建议将它包装在一个单独的对象中,然后你可以存根这个对象,例如:

yt_mock = ... # mocking yt methods you want to use
YouTube.stub :new, yt_mock do
  # controler test
end

您还可以将 YouTube 创建为 class,它接受适配器并将调用委托给它们 - 一个适配器将使用真实的 YT api,另一个只是预定义的答案。