Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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…

like image 242
J. Doe Avatar asked Dec 06 '22 16:12

J. Doe


2 Answers

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.

like image 150
Somar Melkhem Avatar answered Dec 08 '22 06:12

Somar Melkhem


If you run into the error unknown keyword: :format, try this:

describe "GET/index generate CSV" do    
  it "generate CSV" do
    get :index, params: {format: :csv}
    expect(response.header['Content-Type']).to include 'text/csv'
    expect(response.body).to include('what you expect the file to have')
  end
end
like image 39
Thomas Van Holder Avatar answered Dec 08 '22 05:12

Thomas Van Holder