unit test in rails - model with paperclip

VP. picture VP. · Dec 13, 2009 · Viewed 13.8k times · Source

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?

Answer

Max Chernyak picture Max Chernyak · Dec 13, 2009

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

@post = Post.new
@post.attachment = File.new("test/fixtures/sample_file.png")
# Replace attachment= with the name of your paperclip attachment

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.