Simple Improvements and Testing of a Rails Controller

the_teacher

Ilya N. Zykin

Posted on April 21, 2023

Simple Improvements and Testing of a Rails Controller

Simple case how to improve your controller in a Rails application

Step 1. Route to the main page

First I want to check #root route of an App

I go to config/routes.rb and see

Rails.application.routes.draw do
  root to: 'root#index'
end
Enter fullscreen mode Exit fullscreen mode

Step 2. Checking the controller

I visit the controller app/controllers/root_controller.rb

class RootController < ActionController::Base
  def index
    @mailto = "hello@company.com"
    @blogs = Blog
             .published
             .limit(10)
  end
end
Enter fullscreen mode Exit fullscreen mode

Step 3. How to Improve

I see a way to improve the controller. I want to move numbers and strings in constants.

Rule: Do not keep Magic numbers in your code. Always move it constants!

class RootController < ActionController::Base
  MAIN_EMAIL = "hello@company.com"
  INDEX_BLOGS_COUNT = 10

  def index
    @mailto = MAIN_EMAIL
    @blogs = Blog
             .published
             .limit(INDEX_BLOGS_COUNT)
  end
end
Enter fullscreen mode Exit fullscreen mode

Step 4. Adding tests

In my app test environment is already set up. I will just improve existed tests a bit.

require 'rails_helper'

RSpec.describe RootController type: :controller do
  describe 'Constants' do
    it "has expected INDEX_BLOGS_COUNT" do
      expect(RootController::INDEX_BLOGS_COUNT).to eq 10
    end

    it "has expected MAIN_EMAIL" do
      expect(RootController::MAIN_EMAIL).to
        eq("hello@company.com")
    end
  end

  describe '#index' do
    let!(:published_blogs) { create_list :blogs, 3, :published }

    before do
      get :index
    end

    it do
      expect(response).to render_template(:index)
    end

    it do
      expect(assigns(:blogs).map(&:id)).to
        match_array(published_blogs.map(&:id))
    end

    it { expect(assigns(:mailto)).to eq RootController::MAIN_EMAIL }
  end
end
Enter fullscreen mode Exit fullscreen mode

Step 5. Running the test case

bundle exec rspec spec/controllers/root_controller_spec.rb
Enter fullscreen mode Exit fullscreen mode

That is it!
Happy Coding!

💖 💪 🙅 🚩
the_teacher
Ilya N. Zykin

Posted on April 21, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related