ruby-on-railsunit-testingrspecpaperclip

Unit testing paperclip uploads with Rspec (Rails)


Total Rspec noob here. Writing my first tests tonight.

I've got a model called Image. Using paperclip I attach a file called photo. Standard stuff. I've run the paperclip generator and everything works fine in production and test modes.

Now I have a spec file called image.rb and it looks like this (it was created by ryanb's nifty_scaffold generator):

require File.dirname(__FILE__) + '/../spec_helper'

describe Image do

  it "should be valid" do
    Image.new.should be_valid
  end
end

This test fails and I realise that it's because of my model validations (i.e. validates_attachment_presence)

The error that I get is:

Errors: Photo file name must be set., Photo file size file size must be between 0 and 1048576 bytes., Photo content type is not included in the list

So how do I tell rspec to upload a photo when it runs my test?

I'm guessing that it's got somethign to do with fixtures.... maybe not though. I've tried playing around with them but not having any luck. For the record, I've created a folder called images inside my fixtures folder and the two files I want to use in my tests are called rails.png and grid.png)

I've tried doing the following:

it "should be valid" do
  image = Image.new :photo => fixture_file_upload('images/rails.png', 'image/png').should be_valid 

  # I've also tried adding stuff like this
  #image.stub!(:has_attached_file).with(:photo).and_return( true )
  #image.stub!(:save_attached_files).and_return true
  #image.save.should be_true  
end

But rspec complains about "fixture_file_upload" not being recognised... I am planning to get that Rspec book. And I've trawled around the net for an answer but can't seem to find anything. My test database DOES get populated with some data when I remove the validations from my model so I know that some of it works ok.

Thanks in advance,

EDIT:

images.yml looks like this:

one:
  name: MyString
  description: MyString

two:
  name: MyString
  description: MyString

Solution

  • This should work with Rails 2.X:

    Image.new :photo => File.new(RAILS_ROOT + '/spec/fixtures/images/rails.png')
    

    As of Rails 3, RAILS_ROOT is no longer used, instead you should use Rails.root.

    This should work with Rails 3:

    Image.new :photo => File.new(Rails.root + 'spec/fixtures/images/rails.png')
    

    Definitely get the RSpec book, it's fantastic.