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…
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With