I used Paparclip to add a picture to a model, something I did for years. This time I also added a validation for content types, and this might be a first time for me (I don’t want to grep all the models of all the past projects). The validation is
validates_attachment :picture,
content_type: { content_type: ["image/jpg","image/png"] }
Now I want to test it. I was loading real image files in the objects created with FactoryGirl. This is the code
picture { File.open("#{Rails.root}/#{%x[ls test-images/*jpg].split("\n").sample}") }
Note that I’m using %x[].sample to randomly pick an image from a directory, but that’s not important.
The code above doesn’t set a mime type and the validation fails. I had to google quite a lot to find the right hints (some solutions have been obsoleted by newer versions of Paperclip and maybe other parts of the toolchain). The solution is
Rack::Test::UploadedFile.new("#{Rails.root}/#{%x[ls test-images/*jpg].split("\n").sample}"), "image/jpg")
which loads the image and sets it’s content type.