Fabricio Ceciliano
Fabricio Ceciliano

Reputation: 63

How to use controller methods within helper spec?

I am writing the specs test for a data_session_helper_spec file, which looks like this:

data_session_helper_spec.rb

describe "#methods" do
  let(:data_session1) { create(:data_session) }
  let(:data_session2) { create(:data_session) }
  let(:data_session3) { create(:data_session) }

  describe "#collect_sessions_with_today_if_needed" do
    let!(:team) { create(:program_team, data_sessions: [data_session2, data_session3]) }
    let!(:current_user) { create(:user) }

    it "returns an array with all the data sessions :team" do
      session[:current_program_team_id] = team.id

      expect(collect_sessions_with_today_if_needed)
        .to contain_exactly(["Today", 0],
                          [data_session_label(data_session2).to_s, data_session2.id],
                          [data_session_label(data_session3).to_s, data_session3.id])
    end
  end
...
end

The method collect_sessions_with_today_if_needed is declared in the DataSessionHelper file, an it looks like this:

data_session_helper.rb

module DataSessionHelper
  def collect_sessions_with_today_if_needed
    collection = DataSession.by_team(current_program_team)
                        .where("data_sessions.session_date <= ?", Time.zone.now.to_date)
                        .order(session_date: :desc).selector_data.map { |session| [data_session_label(session), session.id] }
    if DataSession.find_by(session_date: Date.current, program_team: current_program_team, user: current_user).present?
      collection
    else
      collection.unshift(["Today", 0])
    end
  end
...
end

When I try running the rspec for data_session_helper_spec, I get an error that current_program_team is undefined and that method is defined in the ApplicationController.

application_controller.rb

class ApplicationController < ActionController::Base
  helper_method :current_program_team
  def current_program_team
    ProgramTeam.friendly.find_by(id: session[:current_program_team_id])
  end

How could I access the application controller methods when running the spec for a helper?

Upvotes: 2

Views: 173

Answers (1)

Artem Shevchenko
Artem Shevchenko

Reputation: 68

It's a bad practice to use session and undefined methods outside of the controller. Prefer to pass this parameters to the method (it will be easy to test). If you want to keep your solution you can do:

let(:helper_class) do
  Class.new do
    include DataSessionHelper
  
    def current_program_team
      ...
    end
  end
end

And test behaviour of this class instance

Upvotes: 1

Related Questions