DEV Community

Ilya N. Zykin
Ilya N. Zykin

Posted on

1

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!

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay