How to test that a file is uploaded in a controller?
Asked Answered
L

1

20

I'm trying to test that my user has a photo value when I upload an image. It works fine in the browser, and the basic functionality of the test passes, but if I try to assert that user.photo is not nil, it fails. Here's the test

describe 'POST #update' do
  context 'when there is an image' do
    it 'renders the crop template' do
      login(user)
      photo = File.open(File.join(Rails.root, '/spec/fixtures/images/bob-weir.jpg'))
      post :update, user: { photo: photo }

      expect(response).to render_template('crop')
      user.reload
      expect(user.photo.file).to_not be_nil
    end
  end
end

is producing:

Failure/Error: expect(user.photo.file).to_not be_nil
       expected: not nil
            got: nil

If I put a debugger at the end of the test and do user.photo, I get:

(byebug) user.photo

#<PhotoUploader:0x007fa447029480 @model=#<User id: 226, ..... photo: nil>,
@mounted_as=:photo, @storage=#<CarrierWave::Storage::File:0x007fa4468ddbb8 
@uploader=#<PhotoUploader:0x007fa447029480 ...>>>

Is there any way to just make sure that the controller actually saved a photo value in the database? Its just an attribute on the model and it saves the filename as a string.

Larch answered 7/1, 2015 at 5:37 Comment(0)
L
31

Answer was to use fixture_file_upload: http://api.rubyonrails.org/classes/ActionDispatch/TestProcess.html#method-i-fixture_file_upload

post :update, user: { photo: fixture_file_upload('images/bob-weir.jpg', 'image/jpg') }

Also, if you wanted to use this in a factory, it would be:

Rack::Test::UploadedFile.new(File.open(File.join(Rails.root, '/spec/fixtures/images/bob-weir.jpg')))
Larch answered 7/1, 2015 at 5:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.