开发者

How do I stub away send_file using mocha

The most direct attempt is to do

@controller.stubs(:send_file)

But that results in an output error like

ActionView::MissingTemplate: Missing template ...

So how do I stub away the send_file met开发者_如何学JAVAhod from 2.3.x series.

The question is basically the same question that was asked on ruby-forum february 2009, which was never really answered.

Jarl


With Rails 4 (and maybe earlier)[1], the ImplicitRender handles this, and it checks against "performed?".

So, if you want to stub it out, stubbing the "performed?" should suffice:

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

The implementation of performed is not that hard either:

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

So, in cases where you don't want, or cannot, stub performed simply ensure the response_body is not nil.


[1] With 5+ this has been moved into BasicImplicitRender.


Missing template errors probably points to the fact that send_file is now not doing anything (because of the stub) so Rails will try to go down the rendering chain and try to display the template.

You've effectively disabled the send_file call now, so you will need to change your stub to actually sends something Rails can interpret and think the request is handled because the file is served, in which case no template will need to be rendered anymore.


I've had to fight with this as well. As far as I can tell, the best solution for me has been:

(controller)

def some_action
  send_file(some_action_filename)
end

private

def some_action_filename
  "/public/something.tgz"
end

(test)

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

I'm not a fan of altering your code to allow you to test, but I am less of a fan of spending hours and hours to find the right solution for a fairly trivial issue :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜