How to test ApplicationController method defined also as a helper method? How to test ApplicationController method defined also as a helper method? ruby-on-rails ruby-on-rails

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


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'  endend

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  endend

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