Skip to content

Commit 4ff1a38

Browse files
committed
Add Avoid Accidentally Disabling Pry as an rspec TIL
1 parent 0bfeb0e commit 4ff1a38

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
1010

1111
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
1212

13-
_1435 TILs and counting..._
13+
_1436 TILs and counting..._
1414

1515
---
1616

@@ -1099,6 +1099,7 @@ _1435 TILs and counting..._
10991099

11001100
### RSpec
11011101

1102+
- [Avoid Accidentally Disabling Pry](rspec/avoid-accidentally-disabling-pry.md)
11021103
- [Check Specific Arguments To Received Method](rspec/check-specific-arguments-to-received-method.md)
11031104
- [Find Minimal Set Of Tests Causing A Flicker](rspec/find-minimal-set-of-tests-causing-a-flicker.md)
11041105
- [Format Test Results As A JSON File](rspec/format-test-results-as-a-json-file.md)
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# Avoid Accidentally Disabling Pry
2+
3+
I was recently working on a test that needed to mock an environment variable in
4+
order to observe the behavior under test. I initially ended up with the
5+
following lines in a `before` block.
6+
7+
```ruby
8+
before do
9+
allow(ENV).to receive(:[]).and_return("")
10+
allow(ENV).to receive(:[]).with("API_SERVER_URL").and_return("localhost")
11+
end
12+
```
13+
14+
The idea was to create a "clean" `ENV` for the test and then layer in any
15+
relevant environment variables from there.
16+
17+
This is a misguided approach for a couple reasons. One particular and
18+
hard-to-debug issue is that this mocking of `ENV` accidentally disabled Pry
19+
(i.e. `binding.pry`). So once I was having issues with my test, I couldn't even
20+
inspect the code at runtime. It would skip right past any `binding.pry`
21+
statement I added.
22+
23+
What happened is that [Pry (specifically `pry-rails`) looks for
24+
`ENV['DISABLE_PRY_RAILS']`](https://github.com/pry/pry-rails/blob/d8d0c6d87a5b8a3e570e0c80910fb80068f3553c/lib/pry-rails.rb#L6)
25+
and if that value is _truthy_ then it won't require the various `pry-rails`
26+
modules.
27+
28+
The first `allow` has `ENV` responding with `""` which is truthy and will
29+
result in Pry being disabled.
30+
31+
A more appropriate default would be `nil`. Also consider that there are many
32+
ways to access `ENV`, such as `#fetch`.

0 commit comments

Comments
 (0)