How to mock request object for rspec helper tests?
Asked Answered
C

4

27

I've a view helper method which generates a url by looking at request.domain and request.port_string.

   module ApplicationHelper  
       def root_with_subdomain(subdomain)  
           subdomain += "." unless subdomain.empty?    
           [subdomain, request.domain, request.port_string].join  
       end  
   end  

I would like to test this method using rspec.

describe ApplicationHelper do
  it "should prepend subdomain to host" do
    root_with_subdomain("test").should = "test.xxxx:xxxx"
  end
end

But when I run this with rspec, I get this:

 Failure/Error: root_with_subdomain("test").should = "test.xxxx:xxxx"
 `undefined local variable or method `request' for #<RSpec::Core::ExampleGroup::Nested_3:0x98b668c>`

Can anyone please help me figure out what should I do to fix this? How can I mock the 'request' object for this example?

Are there any better ways to generate urls where subdomains are used?

Thanks in advance.

Concelebrate answered 27/10, 2010 at 3:59 Comment(0)
O
25

You have to prepend the helper method with 'helper':

describe ApplicationHelper do
  it "should prepend subdomain to host" do
    helper.root_with_subdomain("test").should = "test.xxxx:xxxx"
  end
end

Additionally to test behavior for different request options, you can access the request object throught the controller:

describe ApplicationHelper do
  it "should prepend subdomain to host" do
    controller.request.host = 'www.domain.com'
    helper.root_with_subdomain("test").should = "test.xxxx:xxxx"
  end
end
Optic answered 8/11, 2010 at 14:27 Comment(1)
It is giving error: Exception encountered: #<NameError: undefined local variable or method `controller'. My code looks like controller.request.host = 'lvh.me:3001' expect (helper.request.subdomain).to eq('merchant')Unasked
M
15

This isn't a complete answer to your question, but for the record, you can mock a request using ActionController::TestRequest.new(). Something like:

describe ApplicationHelper do
  it "should prepend subdomain to host" do
    test_domain = 'xxxx:xxxx'
    controller.request = ActionController::TestRequest.new(:host => test_domain)
    helper.root_with_subdomain("test").should = "test.#{test_domain}"
  end
end
Malign answered 4/5, 2012 at 11:24 Comment(0)
U
9

I had a similar problem, i found this solution to work:

before(:each) do
  helper.request.host = "yourhostandorport"
end
Unsuspecting answered 8/6, 2011 at 2:13 Comment(1)
For me in controller it worked with controller.request.host = "http://test_my.com/"Woodrowwoodruff
T
0

This worked for me:

expect_any_instance_of(ActionDispatch::Request).to receive(:domain).exactly(1).times.and_return('domain')
Trude answered 22/1, 2020 at 11:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.