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

后端 未结 5 1756
忘掉有多难
忘掉有多难 2021-02-12 13:36

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:

相关标签:
5条回答
  • 2021-02-12 14:10

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

    0 讨论(0)
  • 2021-02-12 14:14

    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.

    0 讨论(0)
  • 2021-02-12 14:19

    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
    
    0 讨论(0)
  • 2021-02-12 14:26

    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
    
    0 讨论(0)
  • 2021-02-12 14:29

    Try this:

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

    0 讨论(0)
提交回复
热议问题