如何模拟 rspec 辅助测试的请求对象?
我有一个视图辅助方法,它通过查看 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
我想使用 rspec 测试这个方法。
describe ApplicationHelper do
it "should prepend subdomain to host" do
root_with_subdomain("test").should = "test.xxxx:xxxx"
end
end
但是当我用 rspec 运行它时,我得到了这个:
失败/错误:root_with_subdomain("test").should = "test.xxxx:xxxx" `#
的未定义局部变量或方法“请求”`
谁能帮我弄清楚我应该做什么来解决这个问题? 我如何模拟此示例的“请求”对象?
有没有更好的方法来生成使用子域的网址?
提前致谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您必须在辅助方法前面加上“helper”:
此外,为了测试不同请求选项的行为,您可以通过控制器访问请求对象:
You have to prepend the helper method with 'helper':
Additionally to test behavior for different request options, you can access the request object throught the controller:
这不是您问题的完整答案,但为了记录,您可以使用
ActionController::TestRequest.new()
模拟请求。像这样的东西:This isn't a complete answer to your question, but for the record, you can mock a request using
ActionController::TestRequest.new()
. Something like:我遇到了类似的问题,我发现这个解决方案有效:
I had a similar problem, i found this solution to work:
这对我有用:
This worked for me: