简体   繁体   中英

Ruby Rspec AXLSX unit testing error

Here is my code.

wb = xlsx_package.workbook
wb.add_worksheet(name: 'my_work_sheet') do |sheet|
   sheet.add_row ['first row']
end

I have written unit test for above code. Here is it:

it 'should write data in file' do
    workbook = double('Workbook')
    worksheet = double('Worksheet')

    expect(xlsx_package).to receive(:workbook).and_return(workbook)
    expect(workbook).to receive(:add_worksheet).with(name: 'my_work_sheet').and_return(worksheet)
    expect(worksheet).to receive(:add_row).with(['first row'])
end

I am getting error 'xlsx_package' not found

Here's how xlsx_package is assigned:

def self.call(template)
  "xlsx_author = defined?(xlsx_author).nil? ? nil : xlsx_author;\n" +
  "xlsx_created_at = defined?(xlsx_created_at).nil? ? nil : xlsx_created_at;\n" +
  "xlsx_use_shared_strings = defined?(xlsx_use_shared_strings).nil? ? nil : xlsx_use_shared_strings;\n" +
  "xlsx_package = Axlsx::Package.new(\n" +
    ":author => xlsx_author,\n" +
    ":created_at => xlsx_created_at,\n" +
    ":use_shared_strings => xlsx_use_shared_strings\n" +
    ");\n" +
  template.source +
  ";\nxlsx_package.to_stream.string;"
end

https://github.com/straydogstudio/axlsx_rails/blob/afdcf7266b91f3d70c640209702257a635afddc4/lib/axlsx_rails/template_handler.rb#L13

As you can see you can't stub this, but you can change your test a bit:

it 'should write data in file' do
  workbook = double('Workbook')
  worksheet = double('Worksheet')
  xlsx_package = double('Package', workbook: workbook)

  expect(Axlsx::Package).to receive(:new).and_return(xlsx_package)

  expect(xlsx_package).to receive(:workbook).and_return(workbook)
  expect(workbook).to receive(:add_worksheet).with(name: 'my_work_sheet').and_return(worksheet)
  expect(worksheet).to receive(:add_row).with(['first row'])
end

I can't give you the full example because you haven't posted your view template. You also need to understand how the rendering works with the view tests, because your test is still invalid.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM