From 62ddc97d1bd93b1e99baeb775ced1a7f70dbbdc9 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Tue, 22 Aug 2023 14:18:13 -0500 Subject: [PATCH] Add Mock Rails Environment With An Inquiry Instance as a Rails TIL --- README.md | 3 +- ...ls-environment-with-an-inquiry-instance.md | 38 +++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) create mode 100644 rails/mock-rails-environment-with-an-inquiry-instance.md diff --git a/README.md b/README.md index 08d2dd7..23bc74a 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186). -_1335 TILs and counting..._ +_1336 TILs and counting..._ --- @@ -848,6 +848,7 @@ _1335 TILs and counting..._ - [Mask An ActiveRecord Attribute](rails/mask-an-activerecord-attribute.md) - [Merge A Scope Into An ActiveRecord Query](rails/merge-a-scope-into-an-activerecord-query.md) - [Migrating Up Down Up](rails/migrating-up-down-up.md) +- [Mock Rails Environment With An Inquiry Instance](rails/mock-rails-environment-with-an-inquiry-instance.md) - [Order Matters For `rescue_from` Blocks](rails/order-matters-for-rescue-from-blocks.md) - [Params Includes Submission Button Info](rails/params-includes-submission-button-info.md) - [Params Is A Hash With Indifferent Access](rails/params-is-a-hash-with-indifferent-access.md) diff --git a/rails/mock-rails-environment-with-an-inquiry-instance.md b/rails/mock-rails-environment-with-an-inquiry-instance.md new file mode 100644 index 0000000..1b9211d --- /dev/null +++ b/rails/mock-rails-environment-with-an-inquiry-instance.md @@ -0,0 +1,38 @@ +# Mock Rails Environment With An Inquiry Instance + +As discussed in [Make A String Attribute Easy to Inquire +About](make-a-string-attribute-easy-to-inquire-about.md), the `Rails.env` is +assigned an instance of `ActiveSupport::StringInquirer`. This allows us to ask +whether the current Rails environment is `#production?`, `#development?`, etc. + +With this in mind, we can have a test execute in a specific environment by +mocking how `Rails.env` responds. Though the actual env for a test is going to +be `test`, we can simulate a different environment with an RSpec `before` block +like the following: + +```ruby +before do + allow(Rails).to receive(:env) { "staging".inquiry } +end +``` + +Or similarly, to simulate the `production` environment: + +```ruby +before do + allow(Rails).to receive(:env) { "production".inquiry } +end +``` + +The `#inquiry` being monkey-patched onto the `String` class gives you the +willies, you could do the following instead: + +```ruby +before do + allow(Rails).to receive(:env) do + ActiveSupport::StringInquirer.new("production") + end +end +``` + +[source](https://stackoverflow.com/a/25134591/535590)