【问题标题】:RSpec send_file testingRSpec send_file 测试
【发布时间】:2011-06-09 17:20:59
【问题描述】:

如何测试发送文件的控制器动作?

如果我使用controller.should_receive(:send_file) 执行此操作,则测试失败并显示“缺少模板”,因为没有渲染任何内容。

【问题讨论】:

    标签: ruby-on-rails rspec sendfile


    【解决方案1】:

    Googlingaround 看来,render 也会在某些时候被调用.. 但是没有模板,会导致错误。

    解决方案似乎也将其剔除:

    controller.stub!(:render)

    【讨论】:

    • 很好,我怎么没想到 :)
    • 对于使用较新版本的 RSpec 查看此内容的任何人,stub! 已被弃用。只需使用stub
    • 在 Rspec 3 中,它是 allow(controller).to receive(:render)
    【解决方案2】:

    另一种可行的方法是:

    controller.should_receive(:send_file).and_return{controller.render :nothing => true}
    

    对我来说,这体现了send_file 的预期副作用是安排不渲染任何其他内容。 (尽管,让存根调用原始对象上的方法似乎有点不靠谱。)

    【讨论】:

    • Rails 4,RSpec 3:'and_return { value }' is deprecated. Use 'and_return(value)' or an implementation block without 'and_return' instead.
    【解决方案3】:

    您也可以这样做:

    result = get ....
    
    result.body.should eq IO.binread(path_to_file)
    

    【讨论】:

      【解决方案4】:

      这对我在 RSpec 控制器测试中非常有用。我更喜欢不将其存根,而是调用原始文件,以便它返回文件,您甚至可以访问响应标头等...

      expect(controller).to receive(:send_file).with(some_filepath, type: "image/jpg").and_call_original
      

      【讨论】:

        猜你喜欢
        • 2012-02-26
        • 1970-01-01
        • 2014-12-09
        • 2021-09-26
        • 1970-01-01
        • 1970-01-01
        • 2014-05-18
        • 2011-08-27
        • 2017-05-23
        相关资源
        最近更新 更多