如何模拟rspec辅助测试的请求对象?

Bud*_*hiP 22 rspec ruby-on-rails view-helpers rspec2 ruby-on-rails-3

我有一个视图助手方法,它通过查看request.domain和request.port_string来生成一个url.

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

我想用rspec测试这个方法.

describe ApplicationHelper do
  it "should prepend subdomain to host" do
    root_with_subdomain("test").should = "test.xxxx:xxxx"
  end
end
Run Code Online (Sandbox Code Playgroud)

但是当我使用rspec运行时,我得到了这个:

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

任何人都可以帮我弄清楚我该怎么做才能解决这个问题?如何模拟此示例的"请求"对象?

有没有更好的方法来生成使用子域的URL?

提前致谢.

Net*_*rat 22

你必须在'helper'前面加上辅助方法:

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

除了测试不同请求选项的行为外,您还可以通过控制器访问请求对象:

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
Run Code Online (Sandbox Code Playgroud)

  • 它给出错误:遇到异常:#<NameError:未定义的局部变量或方法`controller'.我的代码看起来像controller.request.host ='lvh.me:3001'expect(helper.request.subdomain).to eq('merchant') (2认同)

seb*_*seb 11

这不是您的问题的完整答案,但对于记录,您可以使用模拟请求ActionController::TestRequest.new().就像是:

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
Run Code Online (Sandbox Code Playgroud)


23i*_*use 8

我遇到了类似的问题,我发现这个解决方案有效:

before(:each) do
  helper.request.host = "yourhostandorport"
end
Run Code Online (Sandbox Code Playgroud)