Created
January 25, 2023 14:25
-
-
Save leandro/0c74d1495b5631e27a00523a4be0c509 to your computer and use it in GitHub Desktop.
Injecting controller helper methods inside the helper context in helper methods tests (RSpec)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
class ApplicationController < ActionController::Base | |
helper_method :is_happy? | |
private | |
def is_happy? = true | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
module ApplicationHelper | |
def show_mood_text = is_happy? ? 'Happy' : 'Sad' | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
require 'rails_helper' | |
RSpec.describe ApplicationHelper do | |
describe '#show_mood_text' do | |
subject { helper.show_mood_text } | |
before { inject_controller_helper_methods(ApplicationController) } | |
context 'when is_happy? returns true' do | |
before { allow(helper).to receive(:is_happy?).and_return(true) } | |
it { is_expected.to eq('Happy') } | |
end | |
context 'when is_happy? returns false' do | |
before { allow(helper).to receive(:is_happy?).and_return(false) } | |
it { is_expected.to eq('Sad') } | |
end | |
end | |
def inject_controller_helper_methods(controller_class) | |
helper_module = (controller = controller_class.new)._helpers | |
helper_methods = helper_module.instance_methods(false).sort | |
helper_method = ->(method) { helper_module.instance_method(method) } | |
helper_methods.each do |method| | |
helper.class.define_method(method, helper_method[method]) | |
end | |
helper.controller = controller | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment