Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AXLSX: Parsing xlsx file for rspec tests

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!

like image 654
Sam Shih Avatar asked Aug 11 '15 20:08

Sam Shih


1 Answers

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

like image 172
noel Avatar answered Nov 16 '22 00:11

noel