Testing File Uploads with Webrat and Paperclip
Posted in Code, Ruby on Rails, Tips and Tricks
– Check out some of our more recent Ruby on Rails blog posts. If you’d like to hire our team, get in touch –
I wanted to integrate some branding functionality into an application we’re developing and so I needed test file upload functionality. We’re using Webrat for integration tests, though this will likely change as we increase the amount of Javascript in the app. I added Paperclip to handle the file attachments for logos, and everything was working.
When I added validation to the model, making sure that the file being attached was an image, this broke the tests. It didn’t seem to matter what type the file was, it would fail no matter what on the file type validation.
I used ruby-debug to debug my test and it seems by default Webrat sends file uploads as plain text. It does have the option to specify the file type when attaching the file, so the easiest way around this is just to specify the MIME type for the file. Now my Cucumber step looks something like this :
When /^I attach "([^\"]*)" image to the "([^\"]*)" file field$/ do |filename, field|
type = filename.split(".")[1]
if type == "jpg"
type = "image/jpeg"
end
attach_file field, File.join(RAILS_ROOT, test_asset_path, filename), type
end
Obviously this will need some work as I progress, but it works. At this stage I have an assets folder in my features folder to store any files that I need for my tests.
On the confirmation end of the test I just have a simple tag test to check that the image tag is displaying, and it contains the correct src attribute :
Then /^I should see tag "(.+)"$/ do |selector| (Hpricot(response.body)/selector).should_not be_empty end
So in my feature test I have :
Then I should see tag "img[@src*='']"
This just confirms that there is an image tag that contains the file name of the file that I uploaded in the test.