Unit Test in Rails - Model with Paperclip

unit test in rails - model with paperclip

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.

Unit testing paperclip uploads with Rspec (Rails)

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.

Testing Paperclip file uploading with RSpec

If the model has_attached_file :pic, you should be able to just point the pic attribute at some file and all should be dandy.

Meaning something like @attr = { :pic => File.open(File.join(Rails.root, 'spec', 'fixtures', 'file.png')) }

Fixtures with Paperclip

You can do with fixture_file_upload

include ActionDispatch::TestProcess
Document.create(:asset => fixture_file_upload("#{Rails.root}/path/to/image.png", "image/png"))

or with factory girl

include ActionDispatch::TestProcess

FactoryGirl.define do
factory :asset do
asset { fixture_file_upload("#{Rails.root}/path/to/image.png", "image/png") }
end
end

Where to put files for testing with paperclip

Solved it now:

photo_list = Dir.glob('./test/fixtures/files/images/*.jpg').entries

Person.all.each do |m|
m.avatar = File.open(photo_list.pop)
m.save!
end

How to Minitest Controller :create action with Paperclip Validators

You should just attach an issue using ActionDispatch::TestProcess, fixture_file_upload. Put an image you want to use for your tests in test/fixtures adjust your test to look like this:

test "should create if signed_in" do
sign_in(@user)
image = fixture_file_upload('some_product_image.jpg', 'image/jpg')
assert_difference 'Product.count' do
post :create, product:{ title:'test_product',
description: 'khara',
user_id: @user.id,
image: image
}
end
assert_redirected_to product_path(assigns(:product))
end

This will return an object that pretends to be an uploaded file for paperclip.



Related Topics



Leave a reply



Submit