How to test ApplicationController method defined also as a helper method?

纵然是瞬间 提交于 2019-12-02 17:00:00
Jimmy Cuadra

You can use an anonymous controller to test your ApplicationController, as describe in the RSpec documentation. There's also a section on testing helpers.

You can invoke your helper methods on subject or @controller in the specification.

I have been looking for a solution to this problem and anonymous controller was not what I was looking for. Let's say you have a controller living at app/controllers/application_controller.rb with a simple method which is not bound to a REST path:

class ApplicationController < ActionController:Base

  def your_helper_method
    return 'a_helpful_string'
  end

end

Then you can write your test in spec/controllers/application_controller_spec.rb as follows:

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

While @controller and subject can be used interchangeable here, I would go for subject as its the RSpec idiomatic way for now.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!