About Posts Serving as a Rails Consultant Serving as a Team coach

How to test application helper code with RSpec

24 Sep 2024

  • You don’t have to explicitly include the ApplicationHelper module(via include ApplicationHelper) in the relevant spec to test it

    Sample Code in application_helper.rb

    module ApplicationHelper
      def title
        return t("learner") unless content_for?(:title)
      
        "#{content_for(:title)} | #{t("learner")}"
      end
    end
      
    

    Rspec code in application_helper_spec.rb that works:

    require 'rails_helper'
      
    RSpec.describe ApplicationHelper, type: :helper do
      
      describe '#title' do
        it 'returns page specific title in the context of the app name' do
          content_for(:title) { "Page Title" }
      
          expect(title).to eq("Page Title | #{I18n.t('learner')}")
        end
      
        it 'returns app name when page title is missing' do
          expect(title).to eq("#{I18n.t('learner')}")
        end
      end
    end
      
    
Mohnish Jadwani
Guten Tag/Hello :), I’m Mohnish! This is my blog about my experiences, reflections and learnings as a programmer whose journey started from Bangalore, India as an employee of a company, and after having worked in Singapore for a few years, is currently journeying on as an expat software consultant in Berlin, Germany.