Forum: RSpec Testing a before_filter with a Rails.env condition

4e52f9febb54082914dab8c5ab0b7584?d=identicon&s=25 Shane Mingins (Guest)
on 2011-08-30 01:57
(Received via mailing list)
Hi

We have the occasional ApplicationController before_filter that is
conditioned by the Rails.env and we like the following style:

  before_filter :check_for_something if Rails.env == 'production'

And wish to spec this in an ApplicationController spec using an
anonymous
controller (e.g.
http://relishapp.com/rspec/rspec-rails/docs/contro...
)

*Q. Just wondering how we can Rails.stub(:env).and_return('production')
to
trigger the before_filter?*

As it stands we have moved the conditional down into the method and stub
in
the before(:each)

e.g.

before_filter :check_for_something

def check_for_something
  if Rails.env == 'production'
      ...
  end
end

before(:each) do
  Rails.stub(:env).and_return('production')
 end

Cheers
Shane
5d38ab152e1e3e219512a9859fcd93af?d=identicon&s=25 David Chelimsky (Guest)
on 2011-08-30 05:13
(Received via mailing list)
On Aug 29, 2011, at 6:09 PM, Shane Mingins wrote:

> Hi
>
> We have the occasional ApplicationController before_filter that is conditioned
by the Rails.env and we like the following style:
>
>   before_filter :check_for_something if Rails.env == 'production'

This approach won't work because this line is eval'd once and only once
when the file is loaded.

>
> def check_for_something
>   if Rails.env == 'production'
>       ...
>   end
> end
>
> before(:each) do
>   Rails.stub(:env).and_return('production')
>  end

This approach works because Rails.env inside the check_for_something
method is eval'd each time the method is called.

HTH,
David
4e52f9febb54082914dab8c5ab0b7584?d=identicon&s=25 Shane Mingins (Guest)
on 2011-08-30 06:09
(Received via mailing list)
Yeah sorry I realised that was what was happening.

But thought I'd ask the question in case there might have been something
I
was missing (in the docs) or a smart hack ;-)
This topic is locked and can not be replied to.