Test toggle states with RSpec
Feature toggles are commonly used while developing new features in existing applications. It’s the best alternative to branch-based development.
Feature toggles can be stored along with application code or you can store them separately and use them across services and update them without deploying your application changes. Below are examples of them:
Storing feature toggle in a separate service and accessing those:
require 'httparty_patch'
class ToggleApi
include HTTParty
base_uri TOGGLE_API_URL
class << self
def on? name
put("/read?name=#{name}", headers: {'Content-Type': 'application/json'})
end
end
end
ToggleApi.on?('new_tax_scheme')
Storing toggles in application code:
class Toggle
def self.on?(name)
toggles[name]
end
private
def self.toggles
{
'new_tax_scheme' => true,
'increase_gst' => false
}
end
end
You can choose to achieve it in different ways. We will use the above sample code for reference.
I have created a class where based on toggle we are finding if income is taxable.
class Income < ApplicationRecord
def taxable?
if Toggle.on?('new_tax_scheme')
amount > 500000
else
amount > 250000
end
end
end
To test this behaviour we can stub toggle values to test the behaviour of both states.
require 'rails_helper'
RSpec.describe Income, type: :model do
describe '#eligible_for_tax?' do
context 'when new_tax_scheme toggled on' do
before do
allow(Toggle).to receive(:on?).with('new_tax_scheme').and_return(true)
end
it 'should return true if amount is more than 5L' do
income = Income.new(amount: 600000)
expect(income.taxable?).to be_truthy
end
it 'should return false if amount is less than 5L' do
income = Income.new(amount: 400000)
expect(income.taxable?).to be_falsy
end
end
context 'when new_tax_scheme toggled off' do
before do
allow(Toggle).to receive(:on?).with('new_tax_scheme').and_return(false)
end
it 'should return true if amount is more than 2.5L' do
income = Income.new(amount: 400000)
expect(income.taxable?).to be_truthy
end
it 'should return false if amount is less than 2.5L' do
income = Income.new(amount: 100000)
expect(income.taxable?).to be_falsy
end
end
end
end
If you are maintaining toggles in a separate service you can stub toggle state in a similar way.
allow(ToggleApi).to receive(:on?).with('new_tax_scheme').and_return(false)
Happy Testing!!!