【问题标题】:How to test ApplicationController method defined also as a helper method?如何测试也定义为辅助方法的 ApplicationController 方法?
【发布时间】:2011-06-11 23:11:39
【问题描述】:

在我的 ApplicationController 中,我有一个定义为辅助方法的方法:

helper_method :some_method_here

  • 如何在 RSpec 中测试 ApplicationController?
  • 在测试我的视图/帮助器时如何包含/调用此帮助器方法?

我正在使用带有 RSpec2 的 Rails3

【问题讨论】:

    标签: ruby-on-rails rspec helper rspec2


    【解决方案1】:

    您可以使用 anonymous controller 来测试您的 ApplicationController,如 RSpec 文档中所述。还有一个关于testing helpers的部分。

    【讨论】:

    • 不知何故我错过了那个匿名控制器!谢谢!
    • 正是我需要知道的!
    • 它还在 Rails4 中工作吗?我遇到了No route matches {:controller=>"anonymous", :action => "some action"}..的问题。
    • 可能是这个问题:github.com/rspec/rspec-rails/issues/636。匿名控制器只有默认资源方法的路由,所以将“某些操作”重命名为(比如)“索引”,或者创建一个路由。
    • 我也想为每种我想测试的方法制作路线,但可惜我做不到。所以我只是在 index 的声明中调用了我想测试的每个方法,并使用 allow(controller).to receive(:any_non_relevant_method_name).and_return(true) 为每个单独的测试删除了不相关的方法,我以 DRY 的方式进行了此操作。
    【解决方案2】:

    您可以在规范中调用 subject 或 @controller 上的辅助方法。

    我一直在寻找解决这个问题的方法,而匿名控制器并不是我想要的。假设您有一个住在app/controllers/application_controller.rb 的控制器,它使用了一个未绑定到 REST 路径的简单方法:

    class ApplicationController < ActionController:Base
    
      def your_helper_method
        return 'a_helpful_string'
      end
    
    end
    

    然后您可以在spec/controllers/application_controller_spec.rb 中编写您的测试,如下所示:

    require 'spec_helper'
    
    describe ApplicationController do
    
      describe "#your_helper_method" do
        it "returns a helpful string" do
          expect(subject.your_helper_method).to eq("a_helpful_string")
        end
      end
    
    end
    

    虽然@controller 和subject 可以在这里互换使用,但我现在会选择subject 作为它的RSpec 惯用方式。

    【讨论】:

    • 使用你的答案来测试current_user helper,它工作正常
    • 这种模式将允许传递规范,即使对于尚未添加到 helper_method 参数的方法也是如此。我更喜欢将辅助方法定义为protected,然后指定expect(subject.send(:your_helper_method)).to eq "a_helpful_string"。
    • 发送是一种黑客行为。不要那样做
    • 黑客可以达到目的,如果这是规范的做法,请参考替代方法。另外,发送是语言规范的一部分是有原因的。
    猜你喜欢
    • 2014-11-19
    • 1970-01-01
    • 2010-12-24
    • 1970-01-01
    • 2011-08-03
    • 1970-01-01
    • 2011-11-19
    • 2013-06-11
    • 1970-01-01
    相关资源
    最近更新 更多