我正在开发一个rails 3.2应用程序,用户可以用它下载pdfs。我非常喜欢使用rspec和with进行测试驱动的开发,但我对此感到困惑。
我的控制器中有以下代码:
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,会很好。
谢谢!
发布于 2013-03-07 19:46:06
不知道为什么会出现这种故障,但是您可以测试响应头:
response_headers["Content-Type"].should == "application/pdf"
response_headers["Content-Disposition"].should == "attachment; filename=\"<invoice_name>.pdf\""您要求提供关于更好的测试覆盖率的建议。我想我应该推荐这个:https://www.destroyallsoftware.com/screencasts。这些屏幕对我对测试驱动开发的理解产生了巨大的影响--强烈推荐!
发布于 2016-11-05 20:58:13
我建议使用pdf-检查员 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
endhttps://stackoverflow.com/questions/15277351
复制相似问题