我正在使用wicked_pdf gem,而我目前正试图加速我的规范套件。
我意识到我的一些规格在我的tmp文件夹中生成PDF,这非常耗时。
有没有办法完全存根wicked_pdf,所以它实际上不会生成PDF?
答案 0 :(得分:1)
这取决于你如何使用它,以及你想在测试套件中减少多少,但可能是一个好地方WickedPdf::PdfHelper#make_pdf
,你可以在RSpec测试中使用这样的东西存根:
describe MyController do
describe '#show.pdf' do
it 'creates a PDF'
let(:tiny_pdf) do
# What is the smallest possible valid PDF?
# https://stackoverflow.com/a/17280876/23915
"%PDF-1.4\ntrailer<</Root<</Pages<</Kids[<</MediaBox[0 0 3 3]>>]>>>>>>"
end
# Here is the actual stubbing
allow(WickedPdf::PdfHelper).to receive(:make_pdf).and_return tiny_pdf
get :show, params: { id: 1, format: :pdf }
expect(response.status).to eq 200
end
end
end
或者您可以通过重新打开类并更改定义来全局覆盖它:
if Rails.env.test?
class WickedPdf
class PdfHelper
def make_pdf(options = {})
"%PDF-1.4\ntrailer<</Root<</Pages<</Kids[<</MediaBox[0 0 3 3]>>]>>>>>>"
end
end
end
end
答案 1 :(得分:0)
将WickedPdf::PdfHelper#make_pdf
除去其他答案中的内容会阻止测试使用来渲染的内容。 expect(response).to render_template("show")
。
要找出导致写入文件的方法,我在expect(File).not_to receive(:open)
之前临时添加了get ... format: :pdf
并发现:
Failure/Error: render pdf: "...", template: "show"
(File (class)).open("/tmp/wicked_pdf20200304-24076-r7r1eh.html", 194, {:perm=>384})
expected: 0 times with any arguments
received: 1 time with arguments: ("/tmp/wicked_pdf20200304-24076-r7r1eh.html", 194, {:perm=>384})
# /usr/local/bundle/gems/wicked_pdf-1.4.0/lib/wicked_pdf/tempfile.rb:10:in `initialize'
# /usr/local/bundle/gems/wicked_pdf-1.4.0/lib/wicked_pdf.rb:58:in `new'
# /usr/local/bundle/gems/wicked_pdf-1.4.0/lib/wicked_pdf.rb:58:in `pdf_from_string'
# /usr/local/bundle/gems/wicked_pdf-1.4.0/lib/wicked_pdf/pdf_helper.rb:91:in `make_pdf'
# /usr/local/bundle/gems/wicked_pdf-1.4.0/lib/wicked_pdf/pdf_helper.rb:113:in `make_and_send_pdf'
# /usr/local/bundle/gems/wicked_pdf-1.4.0/lib/wicked_pdf/pdf_helper.rb:40:in `render_with_wicked_pdf'
# /usr/local/bundle/gems/wicked_pdf-1.4.0/lib/wicked_pdf/pdf_helper.rb:30:in `render'
# ./app/controllers/reports_controller.rb:21:in `block (2 levels) in show'
# ./app/controllers/reports_controller.rb:11:in `show'
然后,我在回溯中的不同位置进行了存根测试,发现以下内容使测试与通常的“ html”控制器测试一样快,同时仍然允许测试render_template("show")
:
it "returns http success" do
allow_any_instance_of(WickedPdf::PdfHelper).to receive(:make_and_send_pdf)
get :show, params: { id: 1, format: :pdf }
expect(response).to have_http_status(:success)
end
it "renders the show template" do
allow_any_instance_of(WickedPdf::PdfHelper).to receive(:make_and_send_pdf)
get :show, params: { id: 1, format: :pdf }
expect(response).to render_template("show")
end
这也使得不需要返回微小的pdf。