Search code examples
rubyrspecruby-on-rails-3.2tddrspec-rails

Rspec for exporting to excel?


lib/export.rb

require 'writeexcel'
require "#{Rails.root}/lib/writeexcel"

class Export
  include ApplicationHelper

  def initialize(values)
    @values_ids = values
  end

  def export_existing_data
    # Create a new Excel workbook
    workbook = WriteExcel.new('export.xls')

    # Add a worksheet
    worksheet = workbook.add_worksheet

    format = workbook.add_format  # Add a format
    format.set_bold
    format.set_bg_color('lightblue')
    format.set_align('top')
    format.set_size(12)
    format.set_font('Arial')

    # export codes .......

  end
end

Rspec code

export_spec.rb

require "export"

describe TransformImport do
  let!(:transform_export_usd) do
    TransformImport.new(value_usd.id).export_existing_data 
  end

  context ".export_existing_data" do
    it "should have valid header" do
      # here downloaded_file and export_excel_rows are helper method to compare
      # export excel data, which is fine
      downloaded_file.row(2).should == export_excel_rows
    end
  end
end

PROBLEM

I am getting following error, when running this spec

 Export.export_existing_data should have valid header
     Failure/Error: e = TransformImport.new(value_usd.id).export_existing_data
     NameError:
       uninitialized constant TransformImport::WriteExcel
     # ./lib/transform_export.rb:13:in `export_existing_data'
     # ./spec/lib/transform_export_spec.rb:120:in `block (2 levels) in <top (required)>'

Finished in 18.12 seconds
1 example, 1 failure

What I am missing here. I have properly included require block also. This code is working fine from my application side (i.e when I am clicking on export button from application it is exporting correct data).

I am new to rspec. Please suggest me, what I am doing wrong and what is the proper way to write this spec?

Thanks


Solution

  • Finally I found the problem:

    The problem was, lib/writeexcel. Here writeexcel was having same name as gem 'writeexcel. So instead of requiring actual WriteExcel class from gem, rspec was requiring it from lib/writeexcel and which was causing the problem

    I have created lib/writeexcel for defining colors and other customization. Changing this name to other then writeexcel, rspec properly requiring my gem file and working fine.