代码之家  ›  专栏  ›  技术社区  ›  Dennis Hackethal

使用rspec和pdfkit测试下载pdf

  •  11
  • Dennis Hackethal  · 技术社区  · 12 年前

    我正在开发一个rails 3.2应用程序,用户可以使用它下载pdf。我非常喜欢使用rspec和should匹配器进行测试驱动开发,但我对这一点感到不知所措。

    我的控制器中有以下代码:

    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)会很好。

    谢谢

    2 回复  |  直到 12 年前
        1
  •  17
  •   Jonathan MacDonald    12 年前

    不确定为什么会出现这种故障,但您可以测试响应标头:

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

    您询问了有关提高测试覆盖率的建议。我想我会推荐这个: https://www.destroyallsoftware.com/screencasts 。这些截屏对我对测试驱动开发的理解产生了巨大的影响——强烈推荐!

        2
  •  6
  •   phil pirozhkov    8 年前

    我建议使用 pdf-inspector 用于编写PDF相关Rails操作规范的gem。

    以下是一个示例规范(假设Rails #report 操作写入有关的数据 Ticket 生成的PDF中的模型):

    describe 'GET /report.pdf' do
      it 'returns downloadable PDF with the ticket' do
        ticket = FactoryGirl.create :ticket
    
        get report_path, format: :pdf
    
        expect(response).to be_successful
    
        analysis = PDF::Inspector::Text.analyze response.body
    
        expect(analysis.strings).to include ticket.state
        expect(analysis.strings).to include ticket.title
      end
    end