Rspec — Use mocks in the proper way

Setup

Nobody likes when the controller contains too much business logic and becomes fat. Let's start with one simple controller:

class ReservationsController < ActionController::Base
def create
book = Book.available.find_by(isbn: params[:isbn])

if book
BookReservation.create(user: current_user)
book.update(available_count: book.available_count--)

render :success
else
render :not_found
end
end
end

We have an easy solution to this problem. Extract business logic into a separate Service object and call it from the controller. Before starting the refactoring we should write specs. Always check for specs before the refactoring! Fortunately, we already have them

RSpec.describe ReservationsController, type: :controller do
describe…

Nikita Kharitonov

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store