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

2020-06-07 06:35发布

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.

5条回答
我欲成王,谁敢阻挡
2楼-- · 2020-06-07 07:07

You can override user-agent set in the request env by doing the following.

before(:each) do
  @meth = :abc
  helper.request.user_agent = 'something else'
end

Then, in your spec:

it "does stuff" do
  expect(helper.send(@meth, "some_url")).to # ...
end
查看更多
我想做一个坏孩纸
3楼-- · 2020-06-07 07:12

for those who use request specs instead of controller specs and want to set request.env can do it like this:

Rails.application.env_config["whatever"] = "whatever"

this will make request.env["whatever"] available in your controllers with value you gave it in your specs.

查看更多
一夜七次
4楼-- · 2020-06-07 07:15

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
查看更多
闹够了就滚
5楼-- · 2020-06-07 07:18

Try this:

stub(request).env { {"HTTP_USER_AGENT" => "Some String"} }

查看更多
狗以群分
6楼-- · 2020-06-07 07:26

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

查看更多
登录 后发表回答