88

I have some code that needs to run only if the rails app is in the development environment (i.e. $ rails server) but not in the test environment (i.e. $ rake test).

When I try

if Rails.env.development?
    dont run me during testing
end

the code gets executed regardless of which environment I am in. I've even tried:

if Rails.env.development? and not Rails.env.test?
    NO, REALLY, DONT RUN ME DURING TESTING
end

but no love.

What should I be doing instead?

3
  • This code should work. Have you tried outputting Rails.env inside that block to see what environment Rails thinks it's using?
    – PinnyM
    Commented Mar 18, 2013 at 18:28
  • 1
    I think it could be the "and not" bits.. that is not the same as && ! That is me guessing.. did you find a solution?
    – baash05
    Commented Oct 1, 2014 at 5:43
  • I never found a solution. For whatever reason, rails runs its initializers twice (see comment below). I've since abandoned rails.
    – spierepf
    Commented Oct 2, 2014 at 13:07

1 Answer 1

161

It looks like you're calling it correctly. Perhaps the problem is that the environment is named differently somewhere. Try in the console:

> Rails.env
=> "development"
> Rails.env.development?
=> true
> Rails.env.test?
=> false

...to confirm that the environment is what you think it is.

3
  • 1
    Ok, I've created an initializer which merely 'puts Rails.env'. The result is that $ rails server gives 'development', while $ rake test gives both 'development' and 'test'. This suggests to me that rails is runnning my initializer twice during $ rake test.
    – spierepf
    Commented Mar 18, 2013 at 18:36
  • 2
    You can also open the console in a specific environment, e.g. RAILS_ENV=test rails console.
    – Mori
    Commented Mar 18, 2013 at 19:26
  • 1
    don't worry if you've not installed pry in your app. it works in simple console also
    – Mani
    Commented Oct 12, 2015 at 6:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.