如何使用mocha删除send_file

时间:2011-08-17 13:14:54

标签: ruby-on-rails mocking mocha stubbing

最直接的尝试是

@controller.stubs(:send_file)

但是这会导致输出错误,如

ActionView::MissingTemplate: Missing template ...

那么我该如何删除send_file method from 2.3.x series

这个问题与ruby-forum february 2009提出的问题基本相同,但这个问题从未真正得到解答。

首领

3 个答案:

答案 0 :(得分:2)

使用Rails 4(可能更早)[1],ImplicitRender处理此问题,并检查“已执行?”。

所以,如果你想将其删除,那么“执行?”应该足够了:

subject.stubs(:performed?).returns(true)
subject.expects(:send_file).
  with(image, disposition: "inline")

performed的实施也不是那么难:

performed?
  response_body || (response && response.committed?)
end

因此,如果您不想要或不能,则performed只需确保response_body不是零。

[1]使用5+已将其移至BasicImplicitRender。

答案 1 :(得分:0)

缺少模板错误可能表明send_file现在没有做任何事情(因为存根),所以Rails会尝试沿着渲染链向下并尝试显示模板。

您现在已经有效地禁用了send_file调用,因此您需要更改存根以实际发送Rails可以解释的内容并认为请求已处理,因为文件已提供,在这种情况下不需要呈现模板了。

答案 2 :(得分:0)

我也不得不与此作斗争。据我所知,对我来说最好的解决方案是:

(控制器)

def some_action
  send_file(some_action_filename)
end

private

def some_action_filename
  "/public/something.tgz"
end

(测试)

test "some_action" do
  filename = Rails.root.join("tmp/testfile.tgz")
  assert FileUtils.touch filename  
  @controller.expects(:some_action_filename).at_least_once().returns(filename)
  post :some_action
end

我不喜欢改变您的代码以允许您进行测试,但我不喜欢花费数小时的时间为相当微不足道的问题找到合适的解决方案:)