如何测试ApplicationController方法也定义为辅助方法?

Mir*_*rko 44 rspec ruby-on-rails helper rspec2

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

helper_method :some_method_here

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

我正在使用Rails3和RSpec2

Jim*_*dra 53

您可以使用匿名控制器来测试ApplicationController,如RSpec文档中所述.还有一个关于测试助手的部分.

  • 它还在Rails4中运行吗?我遇到问题`没有路线匹配{:controller =>"anonymous",:action =>"some action"}`.. (2认同)

Kon*_*che 22

您可以在规范中subject@controller在规范中调用辅助方法.

我一直在寻找这个问题的解决方案,匿名控制器不是我想要的.假设你有一个控制器生活在app/controllers/application_controller.rb一个简单的方法,它没有绑定到REST路径:

class ApplicationController < ActionController:Base

  def your_helper_method
    return 'a_helpful_string'
  end

end
Run Code Online (Sandbox Code Playgroud)

然后你可以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
Run Code Online (Sandbox Code Playgroud)

虽然@controller并且subject可以在这里互换使用,但我现在将subject其作为RSpec惯用的方式.