Vishal Nagda Vishal Nagda - 3 months ago 25
Ruby Question

How to test if else condition in rspec

I'm new to RSpec and I want to test if-else condition of a controller, I searched on the internet but the found results are not properly satisfying my search query.

Here is my rails controller:

class ScheduleTimeSlotsController < ApplicationController
def get_available_schedules
if params[:for_date].to_date==Date.today
available_schedules=ScheduleTimeSlot.where(:doctor_id => params[:dr_id],:date=>params[:for_date].to_date,:status=>"vacant",:archive=>false).where("start_time >=?",Time.now.seconds_since_midnight).reorder(:start_time)
else
available_schedules=ScheduleTimeSlot.where(:doctor_id => params[:dr_id],:date=>params[:for_date].to_date,:status=>"vacant",:archive=>false).reorder(:start_time)
end
render :json =>{:available_schedules=>available_schedules}
end
end


I'm using ruby version 2.2.4 and rails version is 4.2.0

Please guide me that how do I write RSpec for this condition, with the help of an example.

Thanks in advance.

Answer

You'll need to run two tests for your controller. In one pass a date that is today, and one that isn't and test the responses. Here:

require 'rails_helper'

RSpec.describe ScheduleTimeSlotsController, type: :controller do
  describe 'GET #get_available_schedules when for_date is today' do
    it 'returns http success' do

    for_date = Date.today
    available_schedules = ScheduleTimeSlot.where(
      doctor_id: params[:dr_id],
      date: params[:for_date].to_date,
      status: 'vacant',
      archive: false
    ).where(
      'start_time >=?',
      Time.now.seconds_since_midnight
    ).reorder(:start_time)

      get 'get_available_schedules', for_date: for_date
      expect(response.body.available_schedules).to eq(available_schedules)
    end
  end

  describe 'GET #get_available_schedules when for_date is not today' do
    it 'returns http success' do

    for_date = Date.yesterday
    available_schedules = ScheduleTimeSlot.where(
      doctor_id: params[:dr_id], date: params[:for_date].to_date,
      status: 'vacant',
      archive: false
    ).reorder(:start_time)

      get 'get_available_schedules', for_date: for_date
      expect(response.body.available_schedules).to eq(available_schedules)
    end
  end
end

Disclaimer: this code is untested, since I don't have access to the actual app.

Comments