【发布时间】:2014-11-19 09:28:22
【问题描述】:
所以我的设置是我的 Rails 应用程序使用了我也在开发的某个 gem。现在我正在为 RSpec 中的 gem 助手编写一些单元测试。 gem 不能自行运行,而是由我的应用程序加载,因此在测试时它是由一个“虚拟”应用程序加载的,该应用程序将应用程序提供的许多功能复制到 gem 中。
我的 gem 助手中的一个方法调用我的(虚拟)应用程序的 ApplicationController 中定义的助手方法,如下所示:
gem 中的方法:
module MyGem::ApplicationHelper
...
def method_to_test()
#do stuff
x()
#do other stuff
end
...
end
下面是为该方法构建测试的方式:
describe MyGem::ApplicationHelper do
...
describe "#method_to_test()" do
it "should do x" do
expect( method_to_test() ).to do_stuff
end
end
...
end
这是(虚拟)应用程序中的方法:
class ApplicationController < ActionController::Base
...
helper_method :x
def x()
# do stuff
end
...
end
问题是当我运行测试时,我得到以下错误:
NoMethod error: undefined method 'x' for #<RSpec::Core::ExampleGroup::Nested_1::Nested_7:0x24ef2645>
我尝试使用以下方法对方法进行存根:
ApplicationController.any_instance.stub(:x)
但我仍然遇到同样的错误。我已经完成了更多的故障排除,但我能想到的唯一想法是包含辅助方法的 ApplicationController 并没有被 RSpec 加载。
编辑:我发现我什至无法从我正在处理的同一个助手中存根方法,例如
module MyGem::ApplicationHelper
...
def method2()
#do stuff
end
def method1()
#do stuff
method2()
#do other stuff
end
...
end
如果我在测试中这样写:
describe MyGem::ApplicationHelper do
...
describe "#method1()" do
it "should do x" do
helper.stub(:method2).and_return(false)
#or:
helper.should_receive(:method2).and_return(false)
expect( method1() ).to do_stuff
end
end
...
end
我的行为与最初的问题相同。我现在很困惑:/
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-3 rspec gem