ruby-on-rails - 使用rspec和pdfkit测试pdf的下载

标签 ruby-on-rails pdf rspec wkhtmltopdf pdfkit

我正在开发一个Rails 3.2应用程序,用户可以使用它下载pdf。我非常喜欢使用rspec和shoulda匹配器进行测试驱动的开发,但是我对此感到茫然。

我的 Controller 中包含以下代码:

def show_as_pdf
  @client = Client.find(params[:client_id])
  @invoice = @client.invoices.find(params[:id])

  PDFKit.configure do |config|
    config.default_options = {
      :footer_font_size => "6",
      :encoding => "UTF-8",
      :margin_top=>"1in",
      :margin_right=>"1in",
      :margin_bottom=>"1in",
      :margin_left=>"1in"
    }
  end

  pdf = PDFKit.new(render_to_string "invoices/pdf", layout: false)
  invoice_stylesheet_path = File.expand_path(File.dirname(__FILE__) + "/../assets/stylesheets/pdfs/invoices.css.scss")
  bootstrap_path = File.expand_path(File.dirname(__FILE__) + "../../../vendor/assets/stylesheets/bootstrap.min.css")

  pdf.stylesheets << invoice_stylesheet_path
  pdf.stylesheets << bootstrap_path
  send_data pdf.to_pdf, filename: "#{@invoice.created_at.strftime("%Y-%m-%d")}_#{@client.name.gsub(" ", "_")}_#{@client.company.gsub(" ", "_")}_#{@invoice.number.gsub(" ", "_")}", type: "application/pdf"
  return true
end

这是相当简单的代码,它所要做的就是配置我的PDFKit并下载生成的pdf。现在,我要测试整个事情,包括:
  • 实例变量的分配(很容易,当然是可行的)
  • 数据发送,即pdf的渲染=>这就是我遇到的问题

  • 我尝试了以下方法:
    controller.should_receive(:send_data)
    

    但这给了我
    Failure/Error: controller.should_receive(:send_data)
       (#<InvoicesController:0x007fd96fa3e580>).send_data(any args)
           expected: 1 time
           received: 0 times
    

    有人知道测试pdf是否已实际下载/发送的方法吗?此外,您还看到什么还应该进行测试才能获得良好的测试覆盖率?例如,测试数据类型(即application/pdf)会很好。

    谢谢!

    最佳答案

    不知道为什么会失败,但是可以测试响应头:

    response_headers["Content-Type"].should == "application/pdf"
    response_headers["Content-Disposition"].should == "attachment; filename=\"<invoice_name>.pdf\""
    

    您要求提供有关更好的测试范围的建议。我以为我会推荐这个:https://www.destroyallsoftware.com/screencasts。这些截屏视频对我对测试驱动开发的理解产生了巨大影响-强烈建议!

    关于ruby-on-rails - 使用rspec和pdfkit测试pdf的下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15277351/

    相关文章:

    java - 将 PDF 转换为具有页面范围的图像

    java - 如何使用 iText 获取 AcroField 属性?

    ruby-on-rails - 使用 rspec 测试 View - 渲染 View 时在帮助文件中未定义 current_user

    ruby-on-rails - Paypal-express gem,在开发中工作但不在生产中

    ruby-on-rails - 列错误地从 HSTORE 返回 key

    android - 如何在Android中获取PDF的当前页码

    ruby-on-rails - CarrierWave stub 请求错误 "Not allowed to upload application/octet-stream files"

    ruby-on-rails - 测试 'create' Controller 操作的正确方法是什么?

    ruby-on-rails - 限制向用户发送大量消息的 "rails way"是什么?

    ruby-on-rails - unicorn 从配置开始失败