【问题标题】:RoR/RSpec - Gem's helper tests cannot access helper methods defined in ApplicationControllerRoR/RSpec - Gem 的辅助测试无法访问 ApplicationController 中定义的辅助方法
【发布时间】: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


    【解决方案1】:

    显然我应该使用helper. 调用我的辅助方法,并在before 块中使用“存根”。所以不要这样做:

    expect( method_to_test() ).to do_stuff
    

    我应该这样做:

    expect( helper.method_to_test() ).to do_stuff
    

    在测试的before 块中使用这个:

    controller.singleton_class.class_eval do
        helper_method :x
        def x()
            #do stuff
        end
    end
    

    此外,有时我会遇到奇怪的错误,我可以通过将helper.method_to_test() 拉出到一个局部变量中来修复,如下所示:

    test_result = helper.method_to_test()
    expect( test_result ).to do_stuff
    

    我不确定变量“trick”为什么有效,但它确实有效,所以我不能抱怨!至于helper. 前缀,我认为没有它,RSpec 不会从正在测试的帮助程序实例本身调用方法。不过,我不确定为什么 NoMethodError 没有失败。

    【讨论】:

    • 您好,我看到了这个,我想我会分享我所知道的。首先,'helper' 方法是 rspec-rails 的一部分。其次,Rails 仅在调用模块时才加载模块,因此变量技巧起作用的原因是 helper.whateveryourmethodis 自动加载模块并为您调用方法。该变量将自动加载启动。
    猜你喜欢
    • 2011-06-11
    • 1970-01-01
    • 1970-01-01
    • 2011-08-03
    • 2015-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多