dch*_*cke 9 pdf rspec ruby-on-rails pdfkit wkhtmltopdf
我正在开发一个rails 3.2应用程序,用户可以使用它下载pdfs.我很喜欢使用rspec和shoulda匹配器进行测试驱动开发,但是我对此感到茫然.
我的控制器里面有以下代码:
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
Run Code Online (Sandbox Code Playgroud)
这是相当简单的代码,它所做的就是配置我的PDFKit并下载生成的pdf.现在我想测试整个事情,包括:
我尝试过以下方法:
controller.should_receive(:send_data)
Run Code Online (Sandbox Code Playgroud)
但这给了我
Failure/Error: controller.should_receive(:send_data)
(#<InvoicesController:0x007fd96fa3e580>).send_data(any args)
expected: 1 time
received: 0 times
Run Code Online (Sandbox Code Playgroud)
有谁知道测试pdf实际下载/发送的方法?此外,您认为还应该测试哪些内容以获得良好的测试覆盖率?例如,测试数据类型,即application/pdf,会很不错.
谢谢!
Jon*_*ald 17
不确定为什么你会遇到这种失败,但你可以测试响应头:
response_headers["Content-Type"].should == "application/pdf"
response_headers["Content-Disposition"].should == "attachment; filename=\"<invoice_name>.pdf\""
Run Code Online (Sandbox Code Playgroud)
您询问了有关更好的测试覆盖率的建议.我以为我会推荐这个:https: //www.destroyallsoftware.com/screencasts.这些截屏视频对我对测试驱动开发的理解产生了巨大影响 - 强烈推荐!
我建议使用pdf-inspector gem 来编写与 PDF 相关的 Rails 操作的规范。
这是一个示例性规范(假设 Rails#report操作在生成的 PDF 中写入有关模型的数据Ticket):
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8087 次 |
| 最近记录: |