views:

789

answers:

2

I'm trying to write a test for a model with a picture, using paperclip. I'm using the test framework default, no shoulda or rspec. In this context, how should I test it? Should I really upload a file? How should I add a file to the fixture?

+4  A: 

Adding file to a model is dead simple. For example:

@post = Post.new
@post.attachment = File.new("test/fixtures/sample_file.png")

In that case you should put the file into your test/fixtures dir.

I usually make a little helper in my test_helper.rb

def sample_file(filename = "sample_file.png")
  File.new("test/fixtures/#{filename}")
end

Then

@post.attachment = sample_file("filename.txt")

If you use something like Factory Girl instead of fixtures this becomes even easier.

hakunin
+2  A: 

This is in Rspec, but can be easily switched over

before do # setup
  @file = File.new(File.join(RAILS_ROOT, "/spec/fixtures/paperclip", "photo.jpg"), 'rb')
  @model = Model.create!(@valid_attributes.merge(:photo => @file))
end

it "should receive photo_file_name from :photo" do # def .... || should ....
  @model.photo_file_name.should == "photo.jpg"
  # assert_true "photo.jpg", @model.photo_file_name
end

Since Paperclip is pretty well tested, I usually don't focus too much on the act of "uploading", unless i'm doing something out of the ordinary. But I will try to focus more on ensuring that the configurations of the attachment, in relation to the model it belongs, meet my needs.

it "should have an attachment :path of :rails_root/path/:basename.:extension" do
  Model.attachment_definitions[:photo][:path].should == ":rails_root/path/:basename.:extension"
  # assert_true ":rails_root/path/:basename.:extension", Model.attachment_definitions[:photo][:path]
end

All the goodies can be found in Model.attachment_definitions.

nowk