RSpec send_file 测试
如何测试发送文件的控制器操作?
如果我使用 controller.should_receive(:send_file)
执行此操作,测试会失败并显示“缺少模板”,因为没有任何内容被渲染。
How to test a controller action that sends a file?
If I do it with controller.should_receive(:send_file)
test fails with "Missing template" because nothing gets rendered.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
来自 谷歌搜索 around,似乎
render
也会在某个时刻被调用..但没有模板,会导致错误。解决方案似乎也是将其存根:
From Googling around, it appears that
render
will also be called at some point .. but with no template, will cause an error.The solution seems to be to stub it out as well:
另一种有效的方法是:
对我来说,这抓住了一个事实,即
send_file
的预期副作用是安排不渲染任何其他内容。 (尽管如此,无可否认,让存根调用原始对象上的方法似乎有点奇怪。)Another way that works is:
To me, this captures the fact that the intended side effect of
send_file
is to arrange that nothing else be rendered. (Albeit, it admittedly seems a bit wonky to have the stub call a method on the original object.)您还可以这样做:
You can also do this:
这对我在 RSpec 控制器测试中非常有用。我更喜欢不将其存根,而是调用原始文件,这样它就会返回文件,您甚至可以访问响应标头等...
This has worked great for me in RSpec controller tests. I prefer to not stub it out, but instead call the original so it does return the file and you can even access the response headers, etc...
如果您正在制定请求规范(您应该 ),监视
send_file
是不可能的。相反,您可以通过检查响应来满足自己:
如果您想断言内容与源文件匹配,则可以,但这通常是过度的,并且对于生成的内容,应在服务层上进行断言。
If you're doing request specs (you should), spying on
send_file
will not be possible.Instead, satisfy yourself with inspecting the response:
If you want to assert that the contents match the source file, you can, but this is generally excessive, and for generated content the assertions should be made on a service layer.