Read more

Pattern: Disabling a certain feature in tests

Dominik Schöler
November 21, 2019Software engineer at makandra GmbH

We now have a similar card on feature flags that covers this topic and more

There is a kind of features in web applications that hinder automated integration tests. Examples include cookie consent banners or form captchas. Clearly, these should be disabled so you do not have to explicitly deal with them in each and every test (like, every test starting with accepting the cookies notice). On the other hand, they must be tested as well.

Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

A good feature disabling solution should therefore meet these requirements:

  • The feature is generally disabled in tests. A test does not need to do anything manually.

  • It is possible to activate the feature manually, so it can be tested specifically.

Suggested solution

Define a constant that is set to true when in test mode:

class ExampleController < BaseController
  
  SKIP_CAPTCHA = Rails.env.test?
  ...

Next, depend activation of that feature on the value of that constant:

  private
  
  def captcha_valid?
    return true if SKIP_CAPTCHA
    ...

To manually activate the feature in tests that actually need it, override the constant:

Given 'bot detection is enabled' do
  stub_const 'ExampleController::SKIP_CAPTCHA', false
end

You may also choose to enable a feature flag using a tag instead:

Before '@captcha' do
  stub_const 'ExampleController::SKIP_CAPTCHA', false
end
Posted by Dominik Schöler to makandra dev (2019-11-21 10:52)