Testing JQuery Upload in Capybara: Files are not attaching

250 Views Asked by At

I am currently building a rails app that uses the jquery-upload plugin to allows users to upload files to do things such as set their user avatar. If the upload is successful, it sets a hidden field on the form with the upload ID, and when the form is submitted, the association is saved. When I manually test this, it works the way it is supposed to. However, I cannot get my RSpec tests to pass.

I am using RSpec as my testing framework and Capybara-webkit as my javascript drive. The field where the file is supposed to attach looks like this

= file_field_tag :file, class: "upload_file_field" (Also, using slim for templating)

The coffeescript that handles the file upload looks like this

$element.fileupload
  dropZone: $dropzoneElement
  url: "/uploads.json"
  method: "PATCH"
  fail: (e, data) =>
    @showErrorOnFailure(e, data)
  done: (e, data) =>
    @onSuccessfulUpload(e, data)

Controller code that handles file uploads looks like this

class UploadsController < ApplicationController
  def create
    @upload = Upload.new(file: params[:file])

    byebug

    if @upload.save
      respond_to do |format|
        format.json { render json: {upload: @upload, url: @upload.file.url(:avatar) } }
      end
    else
      respond_to do |format|
        format.json { render json: {}, status: :unprocessable_entity }
      end
    end
  end
end

And here is the RSpec code I am using in the test to attach the file

filepath = "#{Rails.root}/spec/support/fixtures/uploads/flickr.jpg"
attach_file :file, filepath

click_on "Submit"

expect(page).to have_css(".avatar-img img")

When I run the test, the entire request goes through (Capybara does not indicate it had trouble finding the file or the form field). However, the test fails. And when I use byebug to inspect the uploads controller at the point it receives the request to save a new upload, there are no parameters being sent. As in params[:file] evaluates to nil, when it should have the file information for flickr.jpg. Any idea why my file isn't attaching in the test, even though Capybara isn't raising any errors about it.

1

There are 1 best solutions below

0
Joshua E On

So after reading through this post I found an answer:

Capybara webkit doesn't pass params from angular

It looks like the problem came from the fact that I was using PATCH to send the uploads. After changing the method to PUT, my tests started passing.