Stubbing/Mocking Rails.env with Rspec

This is a quick tip where I’ll show you how to stub (sometimes people also refer to it as mock, but I think stub is more technically correct in this case) Rails.env while writing unit tests for your application.

Why did I have to do this ? Recently while working on an app in a team there was a piece of code that would clear cache on an if condition which looked like this:

What's the one thing every developer wants? More screens! Enhance your coding experience with an external monitor to increase screen real estate.

def clear_cache_in_production
  if Rails.env.production?
    Rails.cache.clear
  end
end

Now while researching how to test this piece of code/unit (method) I came across mocking and stubbing in Rspec and decided to stub Rails.env rather than not writing test for this unit at all.

# Stub
string_inquirer = ActiveSupport::StringInquirer.new('production')
# allow(Class).to receive(:class_method).and_return(return_value)
allow(Rails).to receive(:env).and_return(string_inquirer)

If you don’t know about ActiveSupport::StringInquirer, then here are a couple of helpful articles:

Although note, the :cache_store used will be that specified in your testing environment’s configuration file rather than the production one since Rails.env just returns a string that we stubbed to return something else. This won’t affect the actual configuration we’re using.

Hope that helps!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Author: Rishabh

Rishabh is a full stack web and mobile developer from India. Follow me on Twitter.

Leave a Reply

Your email address will not be published. Required fields are marked *

*