0

I'm trying to figure out how I can test a Rails controller's creation of a file when it's subsequently deleted.

I have a controller that creates a CSV file, sends it to the user, and then deletes it from the server. It looks something like this:

class WelcomeController < ApplicationController
  def download_file
     generate_file
     send_data File.read(filename)
     delete_file
  end

  private

  def generate_file
     # code that creates a file
  end

  def delete_file
     File.delete(filename)
  end
end

My test file:

require "rails_helper"

RSpec.describe WelcomeController :type => :controller do
  describe 'GET #download_file' do
    it 'creates csv files' do
      get :download_file
      expect(File.file?(filename)).to be true # fails because file is deleted
    end
  end
end

I'm trying to test the fact that download_file creates a csv file, however I can't seem to figure out how to tell Rails that I want the delete_file method ignored when in my test environment.

garythegoat
  • 1,517
  • 1
  • 12
  • 25

1 Answers1

1

You can get the current environment with Rails.env

def download_file
  generate_file
  send_data File.read(filename)
  delete_file unless Rails.env.test?
end

It's usually a bad design to have different behavior per environment. Consider instead testing the data sent by send_data (look at this question for an example)

Community
  • 1
  • 1
Baldrick
  • 23,882
  • 6
  • 74
  • 79
  • Thank you - I think testing `send_data` instead makes more sense. I'll try that approach following the question you linked to. – garythegoat Apr 12 '15 at 00:32