Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rspec: how to spec request.env in a helper spec?

Tags:

In my helper module, I have:

def abc(url)   ...   if request.env['HTTP_USER_AGENT']     do something   end end 

In my spec file, I have:

  describe "#abc" do       before(:each) do   @meth = :abc    helper.request.env['HTTP_USER_AGENT'] = "..." end it "should return the webstart jnlp file" do   @obj.send(@meth, "some_url").should .... end end 

When I run the spec I have this error:

undefined local variable or method `request' for <ObjectWithDocHelperMixedIn:0x00000103b5a7d0> 

How do I stub for request.env['...'] in my specs?

Thanks.

like image 267
RoundOutTooSoon Avatar asked Apr 12 '12 21:04

RoundOutTooSoon


People also ask

What should I test in request specs?

Request specs give you the ability to test what your application does, rather than how it does it. For example, instead of testing that the right template is rendered in a controller spec, with a request spec we can test that the content we are expecting to appear actually appears in the response body.

What are request specs?

Request specs allow you to focus on a single controller action, but unlike controller tests involve the router, the middleware stack, and both rack requests and responses. This adds realism to the test that you are writing, and helps avoid many of the issues that are common in controller specs.

What is request Env in Rails?

request. env is a ruby hash that contains information about a visiting user's and server environments. request. env is the standard object that's being used in Rails app to extract important information such as path_info , request_uri etc.

What is a spec in RSpec?

A controller spec is an RSpec wrapper for a Rails functional test. (ActionController::TestCase::Behavior). It allows you to simulate a single http request in each example, and then. specify expected outcomes such as: rendered templates.


2 Answers

If you're using rspec-rails, you might be able to use controller.request in your helper tests.

like image 144
Chris Keele Avatar answered Oct 02 '22 12:10

Chris Keele


Well, you've almost nothing to do:

before(:each) do   @meth = :abc    request.env['HTTP_USER_AGENT'] = "..." end 

I just gave this another try and this passes:

#in helper def foo   request.env['HTTP_USER_AGENT'] end  #spec it "foo" do   helper.request.env['HTTP_USER_AGENT'] = 'foo'   expect(helper.foo).to eq 'foo' end 
like image 26
apneadiving Avatar answered Oct 02 '22 14:10

apneadiving