【发布时间】:2011-06-09 17:20:59
【问题描述】:
如何测试发送文件的控制器动作?
如果我使用controller.should_receive(:send_file) 执行此操作,则测试失败并显示“缺少模板”,因为没有渲染任何内容。
【问题讨论】:
标签: ruby-on-rails rspec sendfile
如何测试发送文件的控制器动作?
如果我使用controller.should_receive(:send_file) 执行此操作,则测试失败并显示“缺少模板”,因为没有渲染任何内容。
【问题讨论】:
标签: ruby-on-rails rspec sendfile
另一种可行的方法是:
controller.should_receive(:send_file).and_return{controller.render :nothing => true}
对我来说,这体现了send_file 的预期副作用是安排不渲染任何其他内容。 (尽管,让存根调用原始对象上的方法似乎有点不靠谱。)
【讨论】:
'and_return { value }' is deprecated. Use 'and_return(value)' or an implementation block without 'and_return' instead.
您也可以这样做:
result = get ....
result.body.should eq IO.binread(path_to_file)
【讨论】:
这对我在 RSpec 控制器测试中非常有用。我更喜欢不将其存根,而是调用原始文件,以便它返回文件,您甚至可以访问响应标头等...
expect(controller).to receive(:send_file).with(some_filepath, type: "image/jpg").and_call_original
【讨论】: