我正在开发一个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。现在,我要测试整个事情,包括:
我尝试了以下方法:
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/