AXLSX: Parsing xlsx file for rspec tests
Asked Answered
P

1

6

Any idea how to write view specs (presence of headers, rows, etc.) for a generated xlsx file from the xlsx gem? Not sure if I'm doing it correctly in the first place but here's what I have so far

RSpec.describe "spreadsheet.xlsx.axlsx", :type =>  :view do
    ...
    it "should have header Books" do
      assign(:spreadsheet, spreadsheet)
      render
      # rendered.rows[0].cells.map(&:value).should include "Books"
    end
end

In pry, rendered is in a utf-8 encoded string I'm not sure how to parse for headers, etc.

=> "PK\u0003\u0004\u0014\u0000\u0000\u0000\b\u0000\u0000\u0000!\xECc8k\xD4\

Is there a way I can just test the generated xlsx file like I would an html view?

Something like...

it "has header Books" do
  assign(:worksheet, worksheet)
  render
  expect(rendered).to have_xpath("(//table)[1]/thead/tr/td", :text => "Books")
end

Thanks in advance!

Podagra answered 11/8, 2015 at 20:25 Comment(0)
B
8

It appears rendered is the raw response so you can use something like the axlsx_rails request specs:

File.open('/tmp/xlsx_temp.xlsx', 'w') {|f| f.write(rendered) }
wb = nil
expect{ wb = Roo::Excelx.new('/tmp/xlsx_temp.xlsx') }.to_not raise_error
wb.cell(2,1).should == 'Some value'

This uses the roo gem to parse the file since Axlsx does not read xlsx.

See: https://github.com/straydogstudio/axlsx_rails/blob/master/spec/axlsx_request_spec.rb#L19-L22

Bisector answered 12/8, 2015 at 21:45 Comment(1)
This worked perfectly, exactly what I needed. Thanks!Hawkweed

© 2022 - 2024 — McMap. All rights reserved.