Search code examples
ruby-on-railsrubycsvruby-on-rails-4rspec

rspec to test respond_to format and csv


I want to test if top_users eq User.top_users in my rspec controller. How do i access the format.csv? I need something like:

it "format csv" do
  get :index, format: :csv
  # expect(something)……
end

Later want to test the csv: if file format is correct, without saving/downloading it.

Controller:

def index
  respond_to do |format|  
    format.csv do
      top_users = User.top_users

      send_data(
        top_users.to_csv,
        filename: "top-users-#{Time.zone.today}.csv"
      )
    end
  end
end

Model:

def self.to_csv
  CSV.generate(headers: true) do |csv|
    csv << [‘one’, ‘two’]

    all.each do |user|
      csv << user.csv_data
    end
  end
end

csv_data is: [user.name, user.email] or so…


Solution

  • It doesn't matter CSV, PDF or something else, it's all about the response that you get from the get request with format csv. This is way i do test my the csv generator:

    describe "GET/index generate CSV" do
      before :each do
        get :index, format: :csv
      end
    
      it "generate CSV" do
        expect(response.header['Content-Type']).to include 'text/csv'
        expect(response.body).to include('what you expect the file to have')
      end
    end
    

    And that's it.

    For each user that you have you can do something like this:

     User.top_users.each do |user|
       expect(response.body).to include(user.name) # or the attr you want to check if it's in the file
     end
    

    you can also add 'pry' gem, put binding.pry before expect and see the response and what elements would be helpful for you to check if the method works correctly as you expect.