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].jo开发者_运维问答in  
       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.
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
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
I had a similar problem, i found this solution to work:
before(:each) do
  helper.request.host = "yourhostandorport"
end
This worked for me:
expect_any_instance_of(ActionDispatch::Request).to receive(:domain).exactly(1).times.and_return('domain')
 
         
                                         
                                         
                                         
                                        ![Interactive visualization of a graph in python [closed]](https://www.devze.com/res/2023/04-10/09/92d32fe8c0d22fb96bd6f6e8b7d1f457.gif) 
                                         
                                         
                                         
                                         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论