Creating Tests with RSpec: Tips, Tools, and Best Practices from Daily Experience

Using rspec and devise token auth on API's scenarios

Posted on August 30, 2024

Global statements

Since the same conditions or at least the same variables will be reused in many scenarios, it's correct to make global declarations available across the scenarios.
How we made those statements, using FactoryBot or Model creation:

FactoryBot
let (:var_name) { 
  create(:model_type, field_1: 'value_1', field_2: 'value_2'..) 
}
Model creation
let(:var_name) { 
     Model.create(field_1: 'value_1', field_2: 'value_2'..) 
}

Use before and after each block

One major requirement with testing is to avoid mix the conditions of the scenarios, to this purpose, rspec offers the before and after each block.

The before each block must be used to define the conditions of the scenario, the conditions of the app and the records.ie

before(:each) do
  #Before the scenario the user is locked  
  user_1.lock_access!
end

before(:each) do
   #The scenarios happens only at 6:00 AM of time zone
  Timecop.travel(Time.zone.now.beginning_of_day + 6.hours)
end
On Rspec the after each block must be used to restore the global conditions, for example, if your scenario is simulated jump on time or update a cache redis keys the after block must restore the default status of the variables, samples:
after(:each) do 
   #Restore the current time
   Timecop.return
end

after(:each) do
  #Restore redis keys to default status
  $redis.set("key_name", key_value)
end

after(:each) do
  #Restore default time zone after tests
  Time.zone = default_time_zone
end

Use gem or helper to simulate jump across time

One of the most common scenarios on testing is simulating we are working on a specific date or weekday, we can use the travel method from Rails or use a gem for this purpose if you are using an older version of Rails, all this setup must be added on the before each block and restore the current time on the after each block.

before(:each) do
  Time.current
  travel 1.day
end

Using Timecop

before(:each) do
  Timecop.travel(1.day.from_now)
end

after(:each) do
   Timecop.return
end
Using Delorean

before(:each) do
  Delorean.time_travel_to(1.day.from_now)
end

after(:each) do
  Delorean.back_to_the_present
end

Define login helpers to login or authenticate on API's


That's a major requirement to test API's or Backoffice actions, so if your are using and authentication method or a gem like devise, so the first step is define this login helper as a global method for rspec.

Create a new file /spec/support/devise_helpers.rb

 module DeviseHelpers
  def login_user(user)
   sign_in user
   request.session[:user] = user.id
  end
 
  def login_api_user(user)
    request.headers['Content-Type'] = 'application/json'
    request.headers.merge! user.create_new_auth_token
    request.session[:user_id] = user.id
  end
 end

Include the helpers on the rspec configuration on spec/rails_helper.rb

RSpec.configure do |config|
   config.include DeviseHelpers, type: :controller
   config.include DeviseHelpers, type: :request
end

So when we have to use it's available across al kind of test, ie:


RSpec.describe SomeController, type: :controller do
  context 'Some scenarios' do
    let(:user) { FactoryBot.create(:user) }
     before(:each) do
        login_user(user)
    end
  end
    it 'Scenario 1' do
   end
   
   it 'Scenario 2' do
   end
end



Execute test with parallelism to run multiple tests

If you are testing request scenarios validating performance or handling multiples request the proper way is using parallelism. Let's imagine the following scenario we have to handle multiple requests at same action and avoid duplicate records, we must send multiple requests, how we do it? Using threads.

context 'Paralellism scenario' do
  let (:user) { create(user, email: Faker::Internet.email) }
  before(:each) do
    
  end

  it 'Send multiples requests' do
    threads = []
    (1..5).each do |index|
      threads << Thread.new do
          post create_new_record_path, params: { ... }
          expect(response.status).to eq 200
      end
    end
   threads.each(&:join)
  end
end

That's a common scenario to validate transactional actions or performance, a useful tool to improve your code behavior.



Add requests to validate flow or performance and controller test to test you code logic


As we mentioned in the parallel test you can use the requests tests to validate code performance, but you can separate the code logic using the controller test, you can separate the logic and performance by the kind of test.

If you have the following scenario, test the expected response time of a request with multiple requests simultaneously.

context 'Validate response time' do
  let (:user) { create(user, email: Faker::Internet.email) }
  before(:each) do
    
  end

  it 'Send multiples requests' do
    threads = []
    (1..5).each do |index|
      threads << Thread.new do
          starting = Process.clock_gettime(Process::CLOCK_MONOTONIC)
          post create_new_record_path, params: { ... }
          expect(response.status).to eq 200
          response_time = Process.clock_gettime(Process::CLOCK_MONOTONIC) - starting)
          expect(response_time).to be <= 10 #expected less than 10 seconds
      end
    end
   threads.each(&:join)
  end
end
And if your have some conditions to validate if your logic is working properly you can use a controller test.


RSpec.describe VisitsController, type: :controller do
  context 'Validate some logic of the code' do
    let (:user) { create(user, email: Faker::Internet.email) } 

    it 'Create a new record' do
       login_user(user)
      post :create, params: {        
          object: {
             field_1: 'value_1',
             field_2: 'value_2'
          }
       }
       json_response = JSON.parse(response.body)
       expect(json_response['success']).to true
       expected_object = json_response['expected_object']
       expect(expect_object['field_3']).to eq true
       expect(expect_object['field_4']).to eq 'expected_value'
     end   
  end
end