我正在尝试理解如何在Rails和MiniTest中工作。我遵循了MiniTest文档的简单示例。我被一个非常简单的例子困住了:
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。
发布于 2018-11-30 13:16:30
您是在使用类方法而不是实例方法:
Clazz.stub :foo, "bar"在常量stub引用的Class类实例上调用Clazz。
您应该在#stub实例上调用Clazz:
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创建为一个类,它接受适配器并将调用委托给它们--一个适配器将使用真正的YT,另一个只是预定义的答案。
https://stackoverflow.com/questions/53558185
复制相似问题