Commit 1f3a7467 by Jon Yurek

Convert all of the tests from test/unit to RSpec

This is a big one.

This change converts all of the existing tests from test/unit to RSpec.
It's been a long time coming, and was specifically prompted by the
inability of minitest to work with Appraisal across the various Rails
versions. Instead of ironing out that headache, converting to RSpec was
preferable (after initial probing).

Many assertions are still assertions and are housed in the Assertions
module, but they should be converted as they get touched. Similarly,
since we're touching all the tests/specs, we convert all the hashes from
1.8 syntax to 1.9 syntax.
parent 73a1fdfd
...@@ -7,12 +7,6 @@ tmp ...@@ -7,12 +7,6 @@ tmp
*.log *.log
test/s3.yml
test/paperclip.db
test/doc
test/pkg
test/tmp
public public
paperclip*.gem paperclip*.gem
capybara*.html capybara*.html
......
...@@ -3,13 +3,13 @@ rvm: ...@@ -3,13 +3,13 @@ rvm:
- jruby-19mode - jruby-19mode
- rbx - rbx
- 2.0.0 - 2.0.0
- 2.1.0 - 2.1.1
install: install:
- "travis_retry bundle install" - "travis_retry bundle install"
before_script: "sudo ntpdate -ub ntp.ubuntu.com pool.ntp.org; true" before_script: "sudo ntpdate -ub ntp.ubuntu.com pool.ntp.org; true"
script: "bundle exec rake clean test cucumber" script: "bundle exec rake clean spec cucumber"
gemfile: gemfile:
- gemfiles/3.2.gemfile - gemfiles/3.2.gemfile
...@@ -21,3 +21,4 @@ matrix: ...@@ -21,3 +21,4 @@ matrix:
allow_failures: allow_failures:
- rvm: jruby-19mode - rvm: jruby-19mode
- rvm: rbx-19mode - rvm: rbx-19mode
- rvm: 2.1.1
appraise "3.0" do
gem "rails", "~> 3.0.20"
gem "paperclip", :path => "../"
end
appraise "3.1" do
gem "rails", "~> 3.1.12"
gem "paperclip", :path => "../"
end
appraise "3.2" do appraise "3.2" do
gem "rails", "~> 3.2.15" gem "rails", "~> 3.2.15"
gem "paperclip", :path => "../" gem "paperclip", :path => "../"
......
...@@ -17,8 +17,9 @@ a test! ...@@ -17,8 +17,9 @@ a test!
5. Push to your fork and submit a pull request. 5. Push to your fork and submit a pull request.
At this point you're waiting on us. We like to at least comment on, if not At this point you're waiting on us. We like to at least comment on, if not
accept, pull requests within three business days (and, typically, one business accept, pull requests within seven business days (most of the work on Paperclip
day). We may suggest some changes or improvements or alternatives. gets done on Fridays). We may suggest some changes or improvements or
alternatives.
Some things that will increase the chance that your pull request is accepted, Some things that will increase the chance that your pull request is accepted,
taken straight from the Ruby on Rails guide: taken straight from the Ruby on Rails guide:
...@@ -35,6 +36,10 @@ Paperclip uses [Appraisal](https://github.com/thoughtbot/appraisal) to aid ...@@ -35,6 +36,10 @@ Paperclip uses [Appraisal](https://github.com/thoughtbot/appraisal) to aid
testing against multiple version of Ruby on Rails. This helps us to make sure testing against multiple version of Ruby on Rails. This helps us to make sure
that Paperclip performs correctly with them. that Paperclip performs correctly with them.
Paperclip also uses [RSpec](http://rspec.info) for its unit tests not. If you
submit tests that are not written for Cucumber or RSpec without a very good
reason, you will be asked to rewrite them before we'll accept.
### Bootstrapping your test suite: ### Bootstrapping your test suite:
bundle install bundle install
...@@ -47,15 +52,15 @@ version of Rails, which defined in `gemfiles/*.gemfile`. ...@@ -47,15 +52,15 @@ version of Rails, which defined in `gemfiles/*.gemfile`.
bundle exec rake bundle exec rake
This will run Test::Unit and Cucumber against all version of Rails This will run RSpec and Cucumber against all version of Rails
### To run single Test::Unit or Cucumber test ### To run single Test::Unit or Cucumber test
You need to specify a `BUNDLE_GEMFILE` pointing to the gemfile before running You need to specify a `BUNDLE_GEMFILE` pointing to the gemfile before running
the normal test command: the normal test command:
BUNDLE_GEMFILE=gemfiles/3.2.gemfile ruby -Itest test/schema_test.rb BUNDLE_GEMFILE=gemfiles/4.1.gemfile rspec spec/paperclip/attachment_spec.rb
BUNDLE_GEMFILE=gemfiles/3.2.gemfile cucumber features/basic_integration.feature BUNDLE_GEMFILE=gemfiles/4.1.gemfile cucumber features/basic_integration.feature
Syntax Syntax
------ ------
......
...@@ -2,12 +2,9 @@ source "https://rubygems.org" ...@@ -2,12 +2,9 @@ source "https://rubygems.org"
gemspec gemspec
gem 'sqlite3', '~> 1.3.4', :platform => :ruby
gem 'jruby-openssl', :platform => :jruby gem 'jruby-openssl', :platform => :jruby
gem 'activerecord-jdbcsqlite3-adapter', :platform => :jruby gem 'activerecord-jdbcsqlite3-adapter', :platform => :jruby
gem 'pry', :platform => :ruby
gem 'pry-byebug', :platform => :ruby
gem 'rubysl', :platform => :rbx gem 'rubysl', :platform => :rbx
# Hinting at development dependencies # Hinting at development dependencies
......
require 'bundler/gem_tasks' require 'bundler/gem_tasks'
require 'appraisal' require 'appraisal'
require 'rake/testtask' require 'rspec/core/rake_task'
require 'cucumber/rake/task' require 'cucumber/rake/task'
desc 'Default: run unit tests.' desc 'Default: run unit tests.'
...@@ -9,19 +9,15 @@ task :default => [:clean, :all] ...@@ -9,19 +9,15 @@ task :default => [:clean, :all]
desc 'Test the paperclip plugin under all supported Rails versions.' desc 'Test the paperclip plugin under all supported Rails versions.'
task :all do |t| task :all do |t|
if ENV['BUNDLE_GEMFILE'] if ENV['BUNDLE_GEMFILE']
exec('rake test cucumber') exec('rake spec cucumber')
else else
Rake::Task["appraisal:install"].execute Rake::Task["appraisal:install"].execute
exec('rake appraisal test cucumber') exec('rake appraisal spec cucumber')
end end
end end
desc 'Test the paperclip plugin.' desc 'Test the paperclip plugin.'
Rake::TestTask.new(:test) do |t| RSpec::Core::RakeTask.new(:spec)
t.libs << 'lib' << 'profile'
t.pattern = 'test/**/*_test.rb'
t.verbose = true
end
desc 'Run integration test' desc 'Run integration test'
Cucumber::Rake::Task.new do |t| Cucumber::Rake::Task.new do |t|
......
...@@ -18,11 +18,11 @@ Feature: Rails integration ...@@ -18,11 +18,11 @@ Feature: Rails integration
And I start the rails application And I start the rails application
When I go to the new user page When I go to the new user page
And I fill in "Name" with "something" And I fill in "Name" with "something"
And I attach the file "test/fixtures/5k.png" to "Attachment" And I attach the file "spec/fixtures/5k.png" to "Attachment"
And I press "Submit" And I press "Submit"
Then I should see "Name: something" Then I should see "Name: something"
And I should see an image with a path of "/paperclip/custom/attachments/original/5k.png" And I should see an image with a path of "/paperclip/custom/attachments/original/5k.png"
And the file at "/paperclip/custom/attachments/original/5k.png" should be the same as "test/fixtures/5k.png" And the file at "/paperclip/custom/attachments/original/5k.png" should be the same as "spec/fixtures/5k.png"
Scenario: Filesystem integration test Scenario: Filesystem integration test
Given I attach :attachment with: Given I attach :attachment with:
...@@ -32,11 +32,11 @@ Feature: Rails integration ...@@ -32,11 +32,11 @@ Feature: Rails integration
And I start the rails application And I start the rails application
When I go to the new user page When I go to the new user page
And I fill in "Name" with "something" And I fill in "Name" with "something"
And I attach the file "test/fixtures/5k.png" to "Attachment" And I attach the file "spec/fixtures/5k.png" to "Attachment"
And I press "Submit" And I press "Submit"
Then I should see "Name: something" Then I should see "Name: something"
And I should see an image with a path of "/system/attachments/original/5k.png" And I should see an image with a path of "/system/attachments/original/5k.png"
And the file at "/system/attachments/original/5k.png" should be the same as "test/fixtures/5k.png" And the file at "/system/attachments/original/5k.png" should be the same as "spec/fixtures/5k.png"
Scenario: S3 Integration test Scenario: S3 Integration test
Given I attach :attachment with: Given I attach :attachment with:
...@@ -55,7 +55,7 @@ Feature: Rails integration ...@@ -55,7 +55,7 @@ Feature: Rails integration
And I start the rails application And I start the rails application
When I go to the new user page When I go to the new user page
And I fill in "Name" with "something" And I fill in "Name" with "something"
And I attach the file "test/fixtures/5k.png" to "Attachment" on S3 And I attach the file "spec/fixtures/5k.png" to "Attachment" on S3
And I press "Submit" And I press "Submit"
Then I should see "Name: something" Then I should see "Name: something"
And I should see an image with a path of "http://s3.amazonaws.com/paperclip/attachments/original/5k.png" And I should see an image with a path of "http://s3.amazonaws.com/paperclip/attachments/original/5k.png"
......
module AttachmentHelpers module AttachmentHelpers
def fixture_path(filename) def fixture_path(filename)
File.expand_path("#{PROJECT_ROOT}/test/fixtures/#{filename}") File.expand_path("#{PROJECT_ROOT}/spec/fixtures/#{filename}")
end end
def attachment_path(filename) def attachment_path(filename)
......
require 'aruba/cucumber' require 'aruba/cucumber'
require 'capybara/cucumber' require 'capybara/cucumber'
require 'test/unit/assertions' require 'rspec/matchers'
$CUCUMBER=1 $CUCUMBER=1
World(Test::Unit::Assertions) World(RSpec::Matchers)
Before do Before do
@aruba_timeout_seconds = 120 @aruba_timeout_seconds = 120
......
...@@ -2,9 +2,10 @@ ...@@ -2,9 +2,10 @@
source "https://rubygems.org" source "https://rubygems.org"
gem "sqlite3", "~> 1.3.4", :platform=>:ruby
gem "jruby-openssl", :platform=>:jruby gem "jruby-openssl", :platform=>:jruby
gem "activerecord-jdbcsqlite3-adapter", :platform=>:jruby gem "activerecord-jdbcsqlite3-adapter", :platform=>:jruby
gem "pry", :platform=>:ruby gem "rubysl", :platform=>:rbx
gem "rails", "~> 3.2.15" gem "rails", "~> 3.2.15"
gem "paperclip", :path=>"../" gem "paperclip", :path=>"../"
......
...@@ -2,9 +2,10 @@ ...@@ -2,9 +2,10 @@
source "https://rubygems.org" source "https://rubygems.org"
gem "sqlite3", "~> 1.3.4", :platform=>:ruby
gem "jruby-openssl", :platform=>:jruby gem "jruby-openssl", :platform=>:jruby
gem "activerecord-jdbcsqlite3-adapter", :platform=>:jruby gem "activerecord-jdbcsqlite3-adapter", :platform=>:jruby
gem "pry", :platform=>:ruby gem "rubysl", :platform=>:rbx
gem "rails", "~> 4.0.0" gem "rails", "~> 4.0.0"
gem "paperclip", :path=>"../" gem "paperclip", :path=>"../"
......
...@@ -2,10 +2,11 @@ ...@@ -2,10 +2,11 @@
source "https://rubygems.org" source "https://rubygems.org"
gem "sqlite3", "~> 1.3.4", :platform=>:ruby
gem "jruby-openssl", :platform=>:jruby gem "jruby-openssl", :platform=>:jruby
gem "activerecord-jdbcsqlite3-adapter", :platform=>:jruby gem "activerecord-jdbcsqlite3-adapter", :platform=>:jruby
gem "sqlite3", :platform=>:ruby gem "rubysl", :platform=>:rbx
gem "rails", "~> 4.1.0.beta" gem "rails", "~> 4.1.0.beta"
gem "paperclip", :path=>"../" gem "paperclip", :path=>"../"
gemspec :path=>"../" gemspec :path=>"../"
\ No newline at end of file
...@@ -16,8 +16,6 @@ class PaperclipGenerator < ActiveRecord::Generators::Base ...@@ -16,8 +16,6 @@ class PaperclipGenerator < ActiveRecord::Generators::Base
migration_template "paperclip_migration.rb.erb", "db/migrate/#{migration_file_name}" migration_template "paperclip_migration.rb.erb", "db/migrate/#{migration_file_name}"
end end
protected
def migration_name def migration_name
"add_attachment_#{attachment_names.join("_")}_to_#{name.underscore.pluralize}" "add_attachment_#{attachment_names.join("_")}_to_#{name.underscore.pluralize}"
end end
......
...@@ -15,7 +15,7 @@ Gem::Specification.new do |s| ...@@ -15,7 +15,7 @@ Gem::Specification.new do |s|
s.rubyforge_project = "paperclip" s.rubyforge_project = "paperclip"
s.files = `git ls-files`.split("\n") s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.test_files = `git ls-files -- {spec,features}/*`.split("\n")
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
s.require_paths = ["lib"] s.require_paths = ["lib"]
...@@ -29,12 +29,12 @@ Gem::Specification.new do |s| ...@@ -29,12 +29,12 @@ Gem::Specification.new do |s|
s.add_development_dependency('activerecord', '>= 3.0.0') s.add_development_dependency('activerecord', '>= 3.0.0')
s.add_development_dependency('shoulda') s.add_development_dependency('shoulda')
s.add_development_dependency('rspec')
s.add_development_dependency('appraisal') s.add_development_dependency('appraisal')
s.add_development_dependency('mocha') s.add_development_dependency('mocha')
s.add_development_dependency('aws-sdk', '>= 1.5.7') s.add_development_dependency('aws-sdk', '>= 1.5.7')
s.add_development_dependency('bourne') s.add_development_dependency('bourne')
s.add_development_dependency('sqlite3', '~> 1.3.4') s.add_development_dependency('cucumber', '~> 1.3.11')
s.add_development_dependency('cucumber', '~> 1.2.1')
s.add_development_dependency('aruba') s.add_development_dependency('aruba')
s.add_development_dependency('nokogiri') s.add_development_dependency('nokogiri')
# Ruby version < 1.9.3 can't install capybara > 2.0.3. # Ruby version < 1.9.3 can't install capybara > 2.0.3.
...@@ -46,4 +46,5 @@ Gem::Specification.new do |s| ...@@ -46,4 +46,5 @@ Gem::Specification.new do |s|
s.add_development_dependency('fakeweb') s.add_development_dependency('fakeweb')
s.add_development_dependency('railties') s.add_development_dependency('railties')
s.add_development_dependency('actionmailer', '>= 3.0.0') s.add_development_dependency('actionmailer', '>= 3.0.0')
s.add_development_dependency('generator_spec')
end end
...@@ -132,4 +132,3 @@ elsif defined?(Test) ...@@ -132,4 +132,3 @@ elsif defined?(Test)
extend Paperclip::Shoulda extend Paperclip::Shoulda
end end
end end
require './test/helper' require 'spec_helper'
class AttachmentDefinitionsTest < Test::Unit::TestCase describe "Attachment Definitions" do
should 'return all of the attachments on the class' do it 'returns all of the attachments on the class' do
reset_class "Dummy" reset_class "Dummy"
Dummy.has_attached_file :avatar, {:path => "abc"} Dummy.has_attached_file :avatar, {:path => "abc"}
Dummy.has_attached_file :other_attachment, {:url => "123"} Dummy.has_attached_file :other_attachment, {:url => "123"}
......
# encoding: utf-8 # encoding: utf-8
require './test/helper' require 'spec_helper'
require 'paperclip/attachment'
class AttachmentProcessingTest < Test::Unit::TestCase
def setup
rebuild_model
end
describe 'Attachment Processing' do
context 'using validates_attachment_content_type' do context 'using validates_attachment_content_type' do
should 'process attachments given a valid assignment' do before do
rebuild_class
end
it 'process attachments given a valid assignment' do
file = File.new(fixture_file("5k.png")) file = File.new(fixture_file("5k.png"))
Dummy.validates_attachment_content_type :avatar, :content_type => "image/png" Dummy.validates_attachment_content_type :avatar, :content_type => "image/png"
instance = Dummy.new instance = Dummy.new
...@@ -18,7 +17,7 @@ class AttachmentProcessingTest < Test::Unit::TestCase ...@@ -18,7 +17,7 @@ class AttachmentProcessingTest < Test::Unit::TestCase
attachment.assign(file) attachment.assign(file)
end end
should 'not process attachments given an invalid assignment with :not' do it 'not process attachments given an invalid assignment with :not' do
file = File.new(fixture_file("5k.png")) file = File.new(fixture_file("5k.png"))
Dummy.validates_attachment_content_type :avatar, :not => "image/png" Dummy.validates_attachment_content_type :avatar, :not => "image/png"
instance = Dummy.new instance = Dummy.new
...@@ -28,7 +27,7 @@ class AttachmentProcessingTest < Test::Unit::TestCase ...@@ -28,7 +27,7 @@ class AttachmentProcessingTest < Test::Unit::TestCase
attachment.assign(file) attachment.assign(file)
end end
should 'not process attachments given an invalid assignment with :content_type' do it 'not process attachments given an invalid assignment with :content_type' do
file = File.new(fixture_file("5k.png")) file = File.new(fixture_file("5k.png"))
Dummy.validates_attachment_content_type :avatar, :content_type => "image/tiff" Dummy.validates_attachment_content_type :avatar, :content_type => "image/tiff"
instance = Dummy.new instance = Dummy.new
...@@ -38,7 +37,7 @@ class AttachmentProcessingTest < Test::Unit::TestCase ...@@ -38,7 +37,7 @@ class AttachmentProcessingTest < Test::Unit::TestCase
attachment.assign(file) attachment.assign(file)
end end
should 'when validation :if clause returns false, allow what would be an invalid assignment' do it 'when validation :if clause returns false, allow what would be an invalid assignment' do
invalid_assignment = File.new(fixture_file("5k.png")) invalid_assignment = File.new(fixture_file("5k.png"))
Dummy.validates_attachment_content_type :avatar, :content_type => "image/tiff", :if => lambda{false} Dummy.validates_attachment_content_type :avatar, :content_type => "image/tiff", :if => lambda{false}
instance = Dummy.new instance = Dummy.new
...@@ -50,7 +49,7 @@ class AttachmentProcessingTest < Test::Unit::TestCase ...@@ -50,7 +49,7 @@ class AttachmentProcessingTest < Test::Unit::TestCase
end end
context 'using validates_attachment' do context 'using validates_attachment' do
should 'process attachments given a valid assignment' do it 'process attachments given a valid assignment' do
file = File.new(fixture_file("5k.png")) file = File.new(fixture_file("5k.png"))
Dummy.validates_attachment :avatar, :content_type => {:content_type => "image/png"} Dummy.validates_attachment :avatar, :content_type => {:content_type => "image/png"}
instance = Dummy.new instance = Dummy.new
...@@ -60,7 +59,7 @@ class AttachmentProcessingTest < Test::Unit::TestCase ...@@ -60,7 +59,7 @@ class AttachmentProcessingTest < Test::Unit::TestCase
attachment.assign(file) attachment.assign(file)
end end
should 'not process attachments given an invalid assignment with :not' do it 'not process attachments given an invalid assignment with :not' do
file = File.new(fixture_file("5k.png")) file = File.new(fixture_file("5k.png"))
Dummy.validates_attachment :avatar, :content_type => {:not => "image/png"} Dummy.validates_attachment :avatar, :content_type => {:not => "image/png"}
instance = Dummy.new instance = Dummy.new
...@@ -70,7 +69,7 @@ class AttachmentProcessingTest < Test::Unit::TestCase ...@@ -70,7 +69,7 @@ class AttachmentProcessingTest < Test::Unit::TestCase
attachment.assign(file) attachment.assign(file)
end end
should 'not process attachments given an invalid assignment with :content_type' do it 'not process attachments given an invalid assignment with :content_type' do
file = File.new(fixture_file("5k.png")) file = File.new(fixture_file("5k.png"))
Dummy.validates_attachment :avatar, :content_type => {:content_type => "image/tiff"} Dummy.validates_attachment :avatar, :content_type => {:content_type => "image/tiff"}
instance = Dummy.new instance = Dummy.new
......
require './test/helper' require 'spec_helper'
require 'paperclip/attachment_registry'
class AttachmentRegistryTest < Test::Unit::TestCase describe 'Attachment Registry' do
def setup before do
Paperclip::AttachmentRegistry.clear Paperclip::AttachmentRegistry.clear
end end
context '.names_for' do context '.names_for' do
should 'include attachment names for the given class' do it 'include attachment names for the given class' do
foo = Class.new foo = Class.new
Paperclip::AttachmentRegistry.register(foo, :avatar, {}) Paperclip::AttachmentRegistry.register(foo, :avatar, {})
assert_equal [:avatar], Paperclip::AttachmentRegistry.names_for(foo) assert_equal [:avatar], Paperclip::AttachmentRegistry.names_for(foo)
end end
should 'not include attachment names for other classes' do it 'not include attachment names for other classes' do
foo = Class.new foo = Class.new
bar = Class.new bar = Class.new
Paperclip::AttachmentRegistry.register(foo, :avatar, {}) Paperclip::AttachmentRegistry.register(foo, :avatar, {})
...@@ -23,13 +22,13 @@ class AttachmentRegistryTest < Test::Unit::TestCase ...@@ -23,13 +22,13 @@ class AttachmentRegistryTest < Test::Unit::TestCase
assert_equal [:lover], Paperclip::AttachmentRegistry.names_for(bar) assert_equal [:lover], Paperclip::AttachmentRegistry.names_for(bar)
end end
should 'produce the empty array for a missing key' do it 'produce the empty array for a missing key' do
assert_empty Paperclip::AttachmentRegistry.names_for(Class.new) assert_empty Paperclip::AttachmentRegistry.names_for(Class.new)
end end
end end
context '.each_definition' do context '.each_definition' do
should 'call the block with the class, attachment name, and options' do it 'call the block with the class, attachment name, and options' do
foo = Class.new foo = Class.new
expected_accumulations = [ expected_accumulations = [
[foo, :avatar, { yo: 'greeting' }], [foo, :avatar, { yo: 'greeting' }],
...@@ -49,7 +48,7 @@ class AttachmentRegistryTest < Test::Unit::TestCase ...@@ -49,7 +48,7 @@ class AttachmentRegistryTest < Test::Unit::TestCase
end end
context '.definitions_for' do context '.definitions_for' do
should 'produce the attachment name and options' do it 'produce the attachment name and options' do
expected_definitions = { expected_definitions = {
avatar: { yo: 'greeting' }, avatar: { yo: 'greeting' },
greeter: { ciao: 'greeting' } greeter: { ciao: 'greeting' }
...@@ -63,7 +62,7 @@ class AttachmentRegistryTest < Test::Unit::TestCase ...@@ -63,7 +62,7 @@ class AttachmentRegistryTest < Test::Unit::TestCase
assert_equal expected_definitions, definitions assert_equal expected_definitions, definitions
end end
should "produce defintions for subclasses" do it "produce defintions for subclasses" do
expected_definitions = { avatar: { yo: 'greeting' } } expected_definitions = { avatar: { yo: 'greeting' } }
Foo = Class.new Foo = Class.new
Bar = Class.new(Foo) Bar = Class.new(Foo)
...@@ -76,7 +75,7 @@ class AttachmentRegistryTest < Test::Unit::TestCase ...@@ -76,7 +75,7 @@ class AttachmentRegistryTest < Test::Unit::TestCase
end end
context '.clear' do context '.clear' do
should 'remove all of the existing attachment definitions' do it 'remove all of the existing attachment definitions' do
foo = Class.new foo = Class.new
Paperclip::AttachmentRegistry.register(foo, :greeter, { ciao: 'greeting' }) Paperclip::AttachmentRegistry.register(foo, :greeter, { ciao: 'greeting' })
......
require './test/helper' require 'spec_helper'
class ContentTypeDetectorTest < Test::Unit::TestCase describe Paperclip::ContentTypeDetector do
should 'give a sensible default when the name is empty' do it 'give a sensible default when the name is empty' do
assert_equal "application/octet-stream", Paperclip::ContentTypeDetector.new("").detect assert_equal "application/octet-stream", Paperclip::ContentTypeDetector.new("").detect
end end
should 'return the empty content type when the file is empty' do it 'return the empty content type when the file is empty' do
tempfile = Tempfile.new("empty") tempfile = Tempfile.new("empty")
assert_equal "inode/x-empty", Paperclip::ContentTypeDetector.new(tempfile.path).detect assert_equal "inode/x-empty", Paperclip::ContentTypeDetector.new(tempfile.path).detect
tempfile.close tempfile.close
end end
should 'return content type of file if it is an acceptable type' do it 'return content type of file if it is an acceptable type' do
MIME::Types.stubs(:type_for).returns([MIME::Type.new('application/mp4'), MIME::Type.new('video/mp4'), MIME::Type.new('audio/mp4')]) MIME::Types.stubs(:type_for).returns([MIME::Type.new('application/mp4'), MIME::Type.new('video/mp4'), MIME::Type.new('audio/mp4')])
Paperclip.stubs(:run).returns("video/mp4") Paperclip.stubs(:run).returns("video/mp4")
@filename = "my_file.mp4" @filename = "my_file.mp4"
assert_equal "video/mp4", Paperclip::ContentTypeDetector.new(@filename).detect assert_equal "video/mp4", Paperclip::ContentTypeDetector.new(@filename).detect
end end
should 'find the right type in the list via the file command' do it 'find the right type in the list via the file command' do
@filename = "#{Dir.tmpdir}/something.hahalolnotreal" @filename = "#{Dir.tmpdir}/something.hahalolnotreal"
File.open(@filename, "w+") do |file| File.open(@filename, "w+") do |file|
file.puts "This is a text file." file.puts "This is a text file."
...@@ -28,12 +28,12 @@ class ContentTypeDetectorTest < Test::Unit::TestCase ...@@ -28,12 +28,12 @@ class ContentTypeDetectorTest < Test::Unit::TestCase
FileUtils.rm @filename FileUtils.rm @filename
end end
should 'return a sensible default if something is wrong, like the file is gone' do it 'return a sensible default if something is wrong, like the file is gone' do
@filename = "/path/to/nothing" @filename = "/path/to/nothing"
assert_equal "application/octet-stream", Paperclip::ContentTypeDetector.new(@filename).detect assert_equal "application/octet-stream", Paperclip::ContentTypeDetector.new(@filename).detect
end end
should 'return a sensible default when the file command is missing' do it 'return a sensible default when the file command is missing' do
Paperclip.stubs(:run).raises(Cocaine::CommandLineError.new) Paperclip.stubs(:run).raises(Cocaine::CommandLineError.new)
@filename = "/path/to/something" @filename = "/path/to/something"
assert_equal "application/octet-stream", Paperclip::ContentTypeDetector.new(@filename).detect assert_equal "application/octet-stream", Paperclip::ContentTypeDetector.new(@filename).detect
......
require './test/helper' require 'spec_helper'
class FileCommandContentTypeDetectorTest < Test::Unit::TestCase describe Paperclip::FileCommandContentTypeDetector do
should 'return a content type based on the content of the file' do it 'return a content type based on the content of the file' do
tempfile = Tempfile.new("something") tempfile = Tempfile.new("something")
tempfile.write("This is a file.") tempfile.write("This is a file.")
tempfile.rewind tempfile.rewind
...@@ -11,14 +11,14 @@ class FileCommandContentTypeDetectorTest < Test::Unit::TestCase ...@@ -11,14 +11,14 @@ class FileCommandContentTypeDetectorTest < Test::Unit::TestCase
tempfile.close tempfile.close
end end
should 'return a sensible default when the file command is missing' do it 'return a sensible default when the file command is missing' do
Paperclip.stubs(:run).raises(Cocaine::CommandLineError.new) Paperclip.stubs(:run).raises(Cocaine::CommandLineError.new)
@filename = "/path/to/something" @filename = "/path/to/something"
assert_equal "application/octet-stream", assert_equal "application/octet-stream",
Paperclip::FileCommandContentTypeDetector.new(@filename).detect Paperclip::FileCommandContentTypeDetector.new(@filename).detect
end end
should 'return a sensible default on the odd chance that run returns nil' do it 'return a sensible default on the odd chance that run returns nil' do
Paperclip.stubs(:run).returns(nil) Paperclip.stubs(:run).returns(nil)
assert_equal "application/octet-stream", assert_equal "application/octet-stream",
Paperclip::FileCommandContentTypeDetector.new("windows").detect Paperclip::FileCommandContentTypeDetector.new("windows").detect
......
# encoding: utf-8 # encoding: utf-8
require './test/helper' require 'spec_helper'
class FilenameCleanerTest < Test::Unit::TestCase describe Paperclip::FilenameCleaner do
should 'convert invalid characters to underscores' do it 'convert invalid characters to underscores' do
cleaner = Paperclip::FilenameCleaner.new(/[aeiou]/) cleaner = Paperclip::FilenameCleaner.new(/[aeiou]/)
assert_equal "b_s_b_ll", cleaner.call("baseball") expect(cleaner.call("baseball")).to eq "b_s_b_ll"
end end
should 'not convert anything if the character regex is nil' do it 'not convert anything if the character regex is nil' do
cleaner = Paperclip::FilenameCleaner.new(nil) cleaner = Paperclip::FilenameCleaner.new(nil)
assert_equal "baseball", cleaner.call("baseball") expect(cleaner.call("baseball")).to eq "baseball"
end end
end end
require './test/helper' require 'spec_helper'
class GeometryDetectorTest < Test::Unit::TestCase describe Paperclip::GeometryDetector do
should 'identify an image and extract its dimensions' do it 'identify an image and extract its dimensions' do
Paperclip::GeometryParser.stubs(:new).with("434x66,").returns(stub(:make => :correct)) Paperclip::GeometryParser.stubs(:new).with("434x66,").returns(stub(:make => :correct))
file = fixture_file("5k.png") file = fixture_file("5k.png")
factory = Paperclip::GeometryDetector.new(file) factory = Paperclip::GeometryDetector.new(file)
output = factory.make output = factory.make
assert_equal :correct, output expect(output).to eq :correct
end end
should 'identify an image and extract its dimensions and orientation' do it 'identify an image and extract its dimensions and orientation' do
Paperclip::GeometryParser.stubs(:new).with("300x200,6").returns(stub(:make => :correct)) Paperclip::GeometryParser.stubs(:new).with("300x200,6").returns(stub(:make => :correct))
file = fixture_file("rotated.jpg") file = fixture_file("rotated.jpg")
factory = Paperclip::GeometryDetector.new(file) factory = Paperclip::GeometryDetector.new(file)
output = factory.make output = factory.make
assert_equal :correct, output expect(output).to eq :correct
end end
end end
require './test/helper' require 'spec_helper'
class GeometryParserTest < Test::Unit::TestCase describe Paperclip::GeometryParser do
should 'identify an image and extract its dimensions with no orientation' do it 'identify an image and extract its dimensions with no orientation' do
Paperclip::Geometry.stubs(:new).with( Paperclip::Geometry.stubs(:new).with(
:height => '73', :height => '73',
:width => '434', :width => '434',
...@@ -15,7 +15,7 @@ class GeometryParserTest < Test::Unit::TestCase ...@@ -15,7 +15,7 @@ class GeometryParserTest < Test::Unit::TestCase
assert_equal :correct, output assert_equal :correct, output
end end
should 'identify an image and extract its dimensions with an empty orientation' do it 'identify an image and extract its dimensions with an empty orientation' do
Paperclip::Geometry.stubs(:new).with( Paperclip::Geometry.stubs(:new).with(
:height => '73', :height => '73',
:width => '434', :width => '434',
...@@ -29,7 +29,7 @@ class GeometryParserTest < Test::Unit::TestCase ...@@ -29,7 +29,7 @@ class GeometryParserTest < Test::Unit::TestCase
assert_equal :correct, output assert_equal :correct, output
end end
should 'identify an image and extract its dimensions and orientation' do it 'identify an image and extract its dimensions and orientation' do
Paperclip::Geometry.stubs(:new).with( Paperclip::Geometry.stubs(:new).with(
:height => '200', :height => '200',
:width => '300', :width => '300',
...@@ -43,7 +43,7 @@ class GeometryParserTest < Test::Unit::TestCase ...@@ -43,7 +43,7 @@ class GeometryParserTest < Test::Unit::TestCase
assert_equal :correct, output assert_equal :correct, output
end end
should 'identify an image and extract its dimensions and modifier' do it 'identify an image and extract its dimensions and modifier' do
Paperclip::Geometry.stubs(:new).with( Paperclip::Geometry.stubs(:new).with(
:height => '64', :height => '64',
:width => '64', :width => '64',
...@@ -57,7 +57,7 @@ class GeometryParserTest < Test::Unit::TestCase ...@@ -57,7 +57,7 @@ class GeometryParserTest < Test::Unit::TestCase
assert_equal :correct, output assert_equal :correct, output
end end
should 'identify an image and extract its dimensions, orientation, and modifier' do it 'identify an image and extract its dimensions, orientation, and modifier' do
Paperclip::Geometry.stubs(:new).with( Paperclip::Geometry.stubs(:new).with(
:height => '50', :height => '50',
:width => '100', :width => '100',
......
require './test/helper' require 'spec_helper'
require 'paperclip/has_attached_file'
class HasAttachedFileTest < Test::Unit::TestCase describe Paperclip::HasAttachedFile do
context '#define_on' do context '#define_on' do
should 'define a setter on the class object' do it 'define a setter on the class object' do
assert_adding_attachment('avatar').defines_method('avatar=') assert_adding_attachment('avatar').defines_method('avatar=')
end end
should 'define a getter on the class object' do it 'define a getter on the class object' do
assert_adding_attachment('avatar').defines_method('avatar') assert_adding_attachment('avatar').defines_method('avatar')
end end
should 'define a query on the class object' do it 'define a query on the class object' do
assert_adding_attachment('avatar').defines_method('avatar?') assert_adding_attachment('avatar').defines_method('avatar?')
end end
should 'define a method on the class to get all of its attachments' do it 'define a method on the class to get all of its attachments' do
assert_adding_attachment('avatar').defines_class_method('attachment_definitions') assert_adding_attachment('avatar').defines_class_method('attachment_definitions')
end end
should 'flush errors as part of validations' do it 'flush errors as part of validations' do
assert_adding_attachment('avatar').defines_validation assert_adding_attachment('avatar').defines_validation
end end
should 'register the attachment with Paperclip::AttachmentRegistry' do it 'register the attachment with Paperclip::AttachmentRegistry' do
assert_adding_attachment('avatar').registers_attachment assert_adding_attachment('avatar').registers_attachment
end end
should 'define an after_save callback' do it 'define an after_save callback' do
assert_adding_attachment('avatar').defines_callback('after_save') assert_adding_attachment('avatar').defines_callback('after_save')
end end
should 'define a before_destroy callback' do it 'define a before_destroy callback' do
assert_adding_attachment('avatar').defines_callback('before_destroy') assert_adding_attachment('avatar').defines_callback('before_destroy')
end end
should 'define an after_commit callback' do it 'define an after_commit callback' do
assert_adding_attachment('avatar').defines_callback('after_commit') assert_adding_attachment('avatar').defines_callback('after_commit')
end end
should 'define the Paperclip-specific callbacks' do it 'define the Paperclip-specific callbacks' do
assert_adding_attachment('avatar').defines_callback('define_paperclip_callbacks') assert_adding_attachment('avatar').defines_callback('define_paperclip_callbacks')
end end
end end
...@@ -52,7 +51,7 @@ class HasAttachedFileTest < Test::Unit::TestCase ...@@ -52,7 +51,7 @@ class HasAttachedFileTest < Test::Unit::TestCase
class AttachmentAdder class AttachmentAdder
include Mocha::API include Mocha::API
include Test::Unit::Assertions include RSpec::Matchers
def initialize(attachment_name) def initialize(attachment_name)
@attachment_name = attachment_name @attachment_name = attachment_name
...@@ -63,9 +62,7 @@ class HasAttachedFileTest < Test::Unit::TestCase ...@@ -63,9 +62,7 @@ class HasAttachedFileTest < Test::Unit::TestCase
Paperclip::HasAttachedFile.define_on(a_class, @attachment_name, {}) Paperclip::HasAttachedFile.define_on(a_class, @attachment_name, {})
assert_received(a_class, :define_method) do |expect| expect(a_class).to have_received(:define_method).with(method_name)
expect.with(method_name)
end
end end
def defines_class_method(method_name) def defines_class_method(method_name)
...@@ -74,9 +71,7 @@ class HasAttachedFileTest < Test::Unit::TestCase ...@@ -74,9 +71,7 @@ class HasAttachedFileTest < Test::Unit::TestCase
Paperclip::HasAttachedFile.define_on(a_class, @attachment_name, {}) Paperclip::HasAttachedFile.define_on(a_class, @attachment_name, {})
assert_received(a_class, :extend) do |expect| expect(a_class).to have_received(:extend).with(Paperclip::HasAttachedFile::ClassMethods)
expect.with(Paperclip::HasAttachedFile::ClassMethods)
end
end end
def defines_validation def defines_validation
...@@ -84,9 +79,7 @@ class HasAttachedFileTest < Test::Unit::TestCase ...@@ -84,9 +79,7 @@ class HasAttachedFileTest < Test::Unit::TestCase
Paperclip::HasAttachedFile.define_on(a_class, @attachment_name, {}) Paperclip::HasAttachedFile.define_on(a_class, @attachment_name, {})
assert_received(a_class, :validates_each) do |expect| expect(a_class).to have_received(:validates_each).with(@attachment_name)
expect.with(@attachment_name)
end
end end
def registers_attachment def registers_attachment
...@@ -95,9 +88,7 @@ class HasAttachedFileTest < Test::Unit::TestCase ...@@ -95,9 +88,7 @@ class HasAttachedFileTest < Test::Unit::TestCase
Paperclip::HasAttachedFile.define_on(a_class, @attachment_name, {size: 1}) Paperclip::HasAttachedFile.define_on(a_class, @attachment_name, {size: 1})
assert_received(Paperclip::AttachmentRegistry, :register) do |expect| expect(Paperclip::AttachmentRegistry).to have_received(:register).with(a_class, @attachment_name, {size: 1})
expect.with(a_class, @attachment_name, {size: 1})
end
end end
def defines_callback(callback_name) def defines_callback(callback_name)
...@@ -105,7 +96,7 @@ class HasAttachedFileTest < Test::Unit::TestCase ...@@ -105,7 +96,7 @@ class HasAttachedFileTest < Test::Unit::TestCase
Paperclip::HasAttachedFile.define_on(a_class, @attachment_name, {}) Paperclip::HasAttachedFile.define_on(a_class, @attachment_name, {})
assert_received(a_class, callback_name.to_sym) expect(a_class).to have_received(callback_name.to_sym)
end end
private private
......
require './test/helper' require 'spec_helper'
class AbstractAdapterTest < Test::Unit::TestCase describe Paperclip::AbstractAdapter do
class TestAdapter < Paperclip::AbstractAdapter class TestAdapter < Paperclip::AbstractAdapter
attr_accessor :tempfile attr_accessor :tempfile
...@@ -10,31 +10,31 @@ class AbstractAdapterTest < Test::Unit::TestCase ...@@ -10,31 +10,31 @@ class AbstractAdapterTest < Test::Unit::TestCase
end end
context "content type from file command" do context "content type from file command" do
setup do before do
@adapter = TestAdapter.new @adapter = TestAdapter.new
@adapter.stubs(:path).returns("image.png") @adapter.stubs(:path).returns("image.png")
Paperclip.stubs(:run).returns("image/png\n") Paperclip.stubs(:run).returns("image/png\n")
end end
should "return the content type without newline" do it "return the content type without newline" do
assert_equal "image/png", @adapter.content_type assert_equal "image/png", @adapter.content_type
end end
end end
context "nil?" do context "nil?" do
should "return false" do it "return false" do
assert !TestAdapter.new.nil? assert !TestAdapter.new.nil?
end end
end end
context "delegation" do context "delegation" do
setup do before do
@adapter = TestAdapter.new @adapter = TestAdapter.new
@adapter.tempfile = stub("Tempfile") @adapter.tempfile = stub("Tempfile")
end end
[:binmode, :binmode?, :close, :close!, :closed?, :eof?, :path, :rewind, :unlink].each do |method| [:binmode, :binmode?, :close, :close!, :closed?, :eof?, :path, :rewind, :unlink].each do |method|
should "delegate #{method} to @tempfile" do it "delegate #{method} to @tempfile" do
@adapter.tempfile.stubs(method) @adapter.tempfile.stubs(method)
@adapter.public_send(method) @adapter.public_send(method)
assert_received @adapter.tempfile, method assert_received @adapter.tempfile, method
...@@ -42,18 +42,18 @@ class AbstractAdapterTest < Test::Unit::TestCase ...@@ -42,18 +42,18 @@ class AbstractAdapterTest < Test::Unit::TestCase
end end
end end
should 'get rid of slashes and colons in filenames' do it 'get rid of slashes and colons in filenames' do
@adapter = TestAdapter.new @adapter = TestAdapter.new
@adapter.original_filename = "awesome/file:name.png" @adapter.original_filename = "awesome/file:name.png"
assert_equal "awesome_file_name.png", @adapter.original_filename assert_equal "awesome_file_name.png", @adapter.original_filename
end end
should 'be an assignment' do it 'be an assignment' do
assert TestAdapter.new.assignment? assert TestAdapter.new.assignment?
end end
should 'not be nil' do it 'not be nil' do
assert !TestAdapter.new.nil? assert !TestAdapter.new.nil?
end end
end end
require './test/helper' require 'spec_helper'
require 'pp'
class AttachmentAdapterTest < Test::Unit::TestCase describe Paperclip::AttachmentAdapter do
before do
def setup
rebuild_model :path => "tmp/:class/:attachment/:style/:filename", :styles => {:thumb => '50x50'} rebuild_model :path => "tmp/:class/:attachment/:style/:filename", :styles => {:thumb => '50x50'}
@attachment = Dummy.new.avatar @attachment = Dummy.new.avatar
end end
context "for an attachment" do context "for an attachment" do
setup do before do
@file = File.new(fixture_file("5k.png")) @file = File.new(fixture_file("5k.png"))
@file.binmode @file.binmode
...@@ -18,37 +16,37 @@ class AttachmentAdapterTest < Test::Unit::TestCase ...@@ -18,37 +16,37 @@ class AttachmentAdapterTest < Test::Unit::TestCase
@subject = Paperclip.io_adapters.for(@attachment) @subject = Paperclip.io_adapters.for(@attachment)
end end
teardown do after do
@file.close @file.close
@subject.close @subject.close
end end
should "get the right filename" do it "get the right filename" do
assert_equal "5k.png", @subject.original_filename assert_equal "5k.png", @subject.original_filename
end end
should "force binmode on tempfile" do it "force binmode on tempfile" do
assert @subject.instance_variable_get("@tempfile").binmode? assert @subject.instance_variable_get("@tempfile").binmode?
end end
should "get the content type" do it "get the content type" do
assert_equal "image/png", @subject.content_type assert_equal "image/png", @subject.content_type
end end
should "get the file's size" do it "get the file's size" do
assert_equal 4456, @subject.size assert_equal 4456, @subject.size
end end
should "return false for a call to nil?" do it "return false for a call to nil?" do
assert ! @subject.nil? assert ! @subject.nil?
end end
should "generate a MD5 hash of the contents" do it "generate a MD5 hash of the contents" do
expected = Digest::MD5.file(@file.path).to_s expected = Digest::MD5.file(@file.path).to_s
assert_equal expected, @subject.fingerprint assert_equal expected, @subject.fingerprint
end end
should "read the contents of the file" do it "read the contents of the file" do
expected = @file.read expected = @file.read
actual = @subject.read actual = @subject.read
assert expected.length > 0 assert expected.length > 0
...@@ -59,7 +57,7 @@ class AttachmentAdapterTest < Test::Unit::TestCase ...@@ -59,7 +57,7 @@ class AttachmentAdapterTest < Test::Unit::TestCase
end end
context "for a file with restricted characters in the name" do context "for a file with restricted characters in the name" do
setup do before do
file_contents = IO.read(fixture_file("animated.gif")) file_contents = IO.read(fixture_file("animated.gif"))
@file = StringIO.new(file_contents) @file = StringIO.new(file_contents)
@file.stubs(:original_filename).returns('image:restricted.gif') @file.stubs(:original_filename).returns('image:restricted.gif')
...@@ -70,21 +68,21 @@ class AttachmentAdapterTest < Test::Unit::TestCase ...@@ -70,21 +68,21 @@ class AttachmentAdapterTest < Test::Unit::TestCase
@subject = Paperclip.io_adapters.for(@attachment) @subject = Paperclip.io_adapters.for(@attachment)
end end
teardown do after do
@subject.close @subject.close
end end
should "not generate paths that include restricted characters" do it "not generate paths that include restricted characters" do
assert_no_match(/:/, @subject.path) expect(@subject.path).to_not match(/:/)
end end
should "not generate filenames that include restricted characters" do it "not generate filenames that include restricted characters" do
assert_equal 'image_restricted.gif', @subject.original_filename assert_equal 'image_restricted.gif', @subject.original_filename
end end
end end
context "for a style" do context "for a style" do
setup do before do
@file = File.new(fixture_file("5k.png")) @file = File.new(fixture_file("5k.png"))
@file.binmode @file.binmode
...@@ -97,38 +95,38 @@ class AttachmentAdapterTest < Test::Unit::TestCase ...@@ -97,38 +95,38 @@ class AttachmentAdapterTest < Test::Unit::TestCase
@subject = Paperclip.io_adapters.for(@attachment.styles[:thumb]) @subject = Paperclip.io_adapters.for(@attachment.styles[:thumb])
end end
teardown do after do
@file.close @file.close
@thumb.close @thumb.close
@subject.close @subject.close
end end
should "get the original filename" do it "get the original filename" do
assert_equal "5k.png", @subject.original_filename assert_equal "5k.png", @subject.original_filename
end end
should "force binmode on tempfile" do it "force binmode on tempfile" do
assert @subject.instance_variable_get("@tempfile").binmode? assert @subject.instance_variable_get("@tempfile").binmode?
end end
should "get the content type" do it "get the content type" do
assert_equal "image/png", @subject.content_type assert_equal "image/png", @subject.content_type
end end
should "get the thumbnail's file size" do it "get the thumbnail's file size" do
assert_equal @thumb.size, @subject.size assert_equal @thumb.size, @subject.size
end end
should "return false for a call to nil?" do it "return false for a call to nil?" do
assert ! @subject.nil? assert ! @subject.nil?
end end
should "generate a MD5 hash of the contents" do it "generate a MD5 hash of the contents" do
expected = Digest::MD5.file(@thumb.path).to_s expected = Digest::MD5.file(@thumb.path).to_s
assert_equal expected, @subject.fingerprint assert_equal expected, @subject.fingerprint
end end
should "read the contents of the thumbnail" do it "read the contents of the thumbnail" do
@thumb.rewind @thumb.rewind
expected = @thumb.read expected = @thumb.read
actual = @subject.read actual = @subject.read
......
require './test/helper' require 'spec_helper'
class DataUriAdapterTest < Test::Unit::TestCase describe Paperclip::DataUriAdapter do
after do
def teardown
if @subject if @subject
@subject.close @subject.close
end end
end end
should 'allow a missing mime-type' do it 'allow a missing mime-type' do
adapter = Paperclip.io_adapters.for("data:;base64,#{original_base64_content}") adapter = Paperclip.io_adapters.for("data:;base64,#{original_base64_content}")
assert_equal Paperclip::DataUriAdapter, adapter.class assert_equal Paperclip::DataUriAdapter, adapter.class
end end
context "a new instance" do context "a new instance" do
setup do before do
@contents = "data:image/png;base64,#{original_base64_content}" @contents = "data:image/png;base64,#{original_base64_content}"
@subject = Paperclip.io_adapters.for(@contents) @subject = Paperclip.io_adapters.for(@contents)
end end
should "returns a file name based on the content type" do it "returns a file name based on the content type" do
assert_equal "data.png", @subject.original_filename assert_equal "data.png", @subject.original_filename
end end
should "return a content type" do it "return a content type" do
assert_equal "image/png", @subject.content_type assert_equal "image/png", @subject.content_type
end end
should "return the size of the data" do it "return the size of the data" do
assert_equal 4456, @subject.size assert_equal 4456, @subject.size
end end
should "generate a correct MD5 hash of the contents" do it "generate a correct MD5 hash of the contents" do
assert_equal( assert_equal(
Digest::MD5.hexdigest(Base64.decode64(original_base64_content)), Digest::MD5.hexdigest(Base64.decode64(original_base64_content)),
@subject.fingerprint @subject.fingerprint
) )
end end
should "generate correct fingerprint after read" do it "generate correct fingerprint after read" do
fingerprint = Digest::MD5.hexdigest(@subject.read) fingerprint = Digest::MD5.hexdigest(@subject.read)
assert_equal fingerprint, @subject.fingerprint assert_equal fingerprint, @subject.fingerprint
end end
should "generate same fingerprint" do it "generate same fingerprint" do
assert_equal @subject.fingerprint, @subject.fingerprint assert_equal @subject.fingerprint, @subject.fingerprint
end end
should 'accept a content_type' do it 'accept a content_type' do
@subject.content_type = 'image/png' @subject.content_type = 'image/png'
assert_equal 'image/png', @subject.content_type assert_equal 'image/png', @subject.content_type
end end
should 'accept an original_filename' do it 'accept an original_filename' do
@subject.original_filename = 'image.png' @subject.original_filename = 'image.png'
assert_equal 'image.png', @subject.original_filename assert_equal 'image.png', @subject.original_filename
end end
should "not generate filenames that include restricted characters" do it "not generate filenames that include restricted characters" do
@subject.original_filename = 'image:restricted.png' @subject.original_filename = 'image:restricted.png'
assert_equal 'image_restricted.png', @subject.original_filename assert_equal 'image_restricted.png', @subject.original_filename
end end
should "not generate paths that include restricted characters" do it "not generate paths that include restricted characters" do
@subject.original_filename = 'image:restricted.png' @subject.original_filename = 'image:restricted.png'
assert_no_match /:/, @subject.path expect(@subject.path).to_not match(/:/)
end end
end end
......
require './test/helper' require 'spec_helper'
class EmptyStringAdapterTest < Test::Unit::TestCase
describe Paperclip::EmptyStringAdapter do
context 'a new instance' do context 'a new instance' do
setup do before do
@subject = Paperclip.io_adapters.for('') @subject = Paperclip.io_adapters.for('')
end end
should "return false for a call to nil?" do it "return false for a call to nil?" do
assert !@subject.nil? assert !@subject.nil?
end end
should 'return false for a call to assignment?' do it 'return false for a call to assignment?' do
assert !@subject.assignment? assert !@subject.assignment?
end end
end end
......
require './test/helper' require 'spec_helper'
class FileAdapterTest < Test::Unit::TestCase describe Paperclip::FileAdapter do
context "a new instance" do context "a new instance" do
context "with normal file" do context "with normal file" do
setup do before do
@file = File.new(fixture_file("5k.png")) @file = File.new(fixture_file("5k.png"))
@file.binmode @file.binmode
end end
teardown do after do
@file.close @file.close
@subject.close if @subject @subject.close if @subject
end end
context 'doing normal things' do context 'doing normal things' do
setup do before do
@subject = Paperclip.io_adapters.for(@file) @subject = Paperclip.io_adapters.for(@file)
end end
should "get the right filename" do it "get the right filename" do
assert_equal "5k.png", @subject.original_filename assert_equal "5k.png", @subject.original_filename
end end
should "force binmode on tempfile" do it "force binmode on tempfile" do
assert @subject.instance_variable_get("@tempfile").binmode? assert @subject.instance_variable_get("@tempfile").binmode?
end end
should "get the content type" do it "get the content type" do
assert_equal "image/png", @subject.content_type assert_equal "image/png", @subject.content_type
end end
should "return content type as a string" do it "return content type as a string" do
assert_kind_of String, @subject.content_type expect(@subject.content_type).to be_a String
end end
should "get the file's size" do it "get the file's size" do
assert_equal 4456, @subject.size assert_equal 4456, @subject.size
end end
should "return false for a call to nil?" do it "return false for a call to nil?" do
assert ! @subject.nil? assert ! @subject.nil?
end end
should "generate a MD5 hash of the contents" do it "generate a MD5 hash of the contents" do
expected = Digest::MD5.file(@file.path).to_s expected = Digest::MD5.file(@file.path).to_s
assert_equal expected, @subject.fingerprint assert_equal expected, @subject.fingerprint
end end
should "read the contents of the file" do it "read the contents of the file" do
expected = @file.read expected = @file.read
assert expected.length > 0 assert expected.length > 0
assert_equal expected, @subject.read assert_equal expected, @subject.read
...@@ -55,35 +55,35 @@ class FileAdapterTest < Test::Unit::TestCase ...@@ -55,35 +55,35 @@ class FileAdapterTest < Test::Unit::TestCase
end end
context "file with multiple possible content type" do context "file with multiple possible content type" do
setup do before do
MIME::Types.stubs(:type_for).returns([MIME::Type.new('image/x-png'), MIME::Type.new('image/png')]) MIME::Types.stubs(:type_for).returns([MIME::Type.new('image/x-png'), MIME::Type.new('image/png')])
@subject = Paperclip.io_adapters.for(@file) @subject = Paperclip.io_adapters.for(@file)
end end
should "prefer officially registered mime type" do it "prefer officially registered mime type" do
assert_equal "image/png", @subject.content_type assert_equal "image/png", @subject.content_type
end end
should "return content type as a string" do it "return content type as a string" do
assert_kind_of String, @subject.content_type expect(@subject.content_type).to be_a String
end end
end end
context "file with content type derived from file command on *nix" do context "file with content type derived from file command on *nix" do
setup do before do
MIME::Types.stubs(:type_for).returns([]) MIME::Types.stubs(:type_for).returns([])
Paperclip.stubs(:run).returns("application/vnd.ms-office\n") Paperclip.stubs(:run).returns("application/vnd.ms-office\n")
@subject = Paperclip.io_adapters.for(@file) @subject = Paperclip.io_adapters.for(@file)
end end
should "return content type without newline character" do it "return content type without newline character" do
assert_equal "application/vnd.ms-office", @subject.content_type assert_equal "application/vnd.ms-office", @subject.content_type
end end
end end
end end
context "filename with restricted characters" do context "filename with restricted characters" do
setup do before do
@file = File.open(fixture_file("animated.gif")) do |file| @file = File.open(fixture_file("animated.gif")) do |file|
StringIO.new(file.read) StringIO.new(file.read)
end end
...@@ -91,32 +91,32 @@ class FileAdapterTest < Test::Unit::TestCase ...@@ -91,32 +91,32 @@ class FileAdapterTest < Test::Unit::TestCase
@subject = Paperclip.io_adapters.for(@file) @subject = Paperclip.io_adapters.for(@file)
end end
teardown do after do
@file.close @file.close
@subject.close @subject.close
end end
should "not generate filenames that include restricted characters" do it "not generate filenames that include restricted characters" do
assert_equal 'image_restricted.gif', @subject.original_filename assert_equal 'image_restricted.gif', @subject.original_filename
end end
should "not generate paths that include restricted characters" do it "not generate paths that include restricted characters" do
assert_no_match /:/, @subject.path expect(@subject.path).to_not match(/:/)
end end
end end
context "empty file" do context "empty file" do
setup do before do
@file = Tempfile.new("file_adapter_test") @file = Tempfile.new("file_adapter_test")
@subject = Paperclip.io_adapters.for(@file) @subject = Paperclip.io_adapters.for(@file)
end end
teardown do after do
@file.close @file.close
@subject.close @subject.close
end end
should "provide correct mime-type" do it "provide correct mime-type" do
assert_match %r{.*/x-empty}, @subject.content_type assert_match %r{.*/x-empty}, @subject.content_type
end end
end end
......
require './test/helper' require 'spec_helper'
class HttpUrlProxyAdapterTest < Test::Unit::TestCase describe Paperclip::HttpUrlProxyAdapter do
context "a new instance" do context "a new instance" do
setup do before do
@open_return = StringIO.new("xxx") @open_return = StringIO.new("xxx")
@open_return.stubs(:content_type).returns("image/png") @open_return.stubs(:content_type).returns("image/png")
Paperclip::HttpUrlProxyAdapter.any_instance.stubs(:download_content).returns(@open_return) Paperclip::HttpUrlProxyAdapter.any_instance.stubs(:download_content).returns(@open_return)
...@@ -10,78 +10,78 @@ class HttpUrlProxyAdapterTest < Test::Unit::TestCase ...@@ -10,78 +10,78 @@ class HttpUrlProxyAdapterTest < Test::Unit::TestCase
@subject = Paperclip.io_adapters.for(@url) @subject = Paperclip.io_adapters.for(@url)
end end
teardown do after do
@subject.close @subject.close
end end
should "return a file name" do it "return a file name" do
assert_equal "thoughtbot-logo.png", @subject.original_filename assert_equal "thoughtbot-logo.png", @subject.original_filename
end end
should 'close open handle after reading' do it 'close open handle after reading' do
assert_equal true, @open_return.closed? assert_equal true, @open_return.closed?
end end
should "return a content type" do it "return a content type" do
assert_equal "image/png", @subject.content_type assert_equal "image/png", @subject.content_type
end end
should "return the size of the data" do it "return the size of the data" do
assert_equal @open_return.size, @subject.size assert_equal @open_return.size, @subject.size
end end
should "generate an MD5 hash of the contents" do it "generate an MD5 hash of the contents" do
assert_equal Digest::MD5.hexdigest("xxx"), @subject.fingerprint assert_equal Digest::MD5.hexdigest("xxx"), @subject.fingerprint
end end
should "generate correct fingerprint after read" do it "generate correct fingerprint after read" do
fingerprint = Digest::MD5.hexdigest(@subject.read) fingerprint = Digest::MD5.hexdigest(@subject.read)
assert_equal fingerprint, @subject.fingerprint assert_equal fingerprint, @subject.fingerprint
end end
should "generate same fingerprint" do it "generate same fingerprint" do
assert_equal @subject.fingerprint, @subject.fingerprint assert_equal @subject.fingerprint, @subject.fingerprint
end end
should "return the data contained in the StringIO" do it "return the data contained in the StringIO" do
assert_equal "xxx", @subject.read assert_equal "xxx", @subject.read
end end
should 'accept a content_type' do it 'accept a content_type' do
@subject.content_type = 'image/png' @subject.content_type = 'image/png'
assert_equal 'image/png', @subject.content_type assert_equal 'image/png', @subject.content_type
end end
should 'accept an original_filename' do it 'accept an original_filename' do
@subject.original_filename = 'image.png' @subject.original_filename = 'image.png'
assert_equal 'image.png', @subject.original_filename assert_equal 'image.png', @subject.original_filename
end end
end end
context "a url with query params" do context "a url with query params" do
setup do before do
Paperclip::HttpUrlProxyAdapter.any_instance.stubs(:download_content).returns(StringIO.new("x")) Paperclip::HttpUrlProxyAdapter.any_instance.stubs(:download_content).returns(StringIO.new("x"))
@url = "https://github.com/thoughtbot/paperclip?file=test" @url = "https://github.com/thoughtbot/paperclip?file=test"
@subject = Paperclip.io_adapters.for(@url) @subject = Paperclip.io_adapters.for(@url)
end end
teardown do after do
@subject.close @subject.close
end end
should "return a file name" do it "return a file name" do
assert_equal "paperclip", @subject.original_filename assert_equal "paperclip", @subject.original_filename
end end
end end
context "a url with restricted characters in the filename" do context "a url with restricted characters in the filename" do
setup do before do
Paperclip::HttpUrlProxyAdapter.any_instance.stubs(:download_content).returns(StringIO.new("x")) Paperclip::HttpUrlProxyAdapter.any_instance.stubs(:download_content).returns(StringIO.new("x"))
@url = "https://github.com/thoughtbot/paper:clip.jpg" @url = "https://github.com/thoughtbot/paper:clip.jpg"
@subject = Paperclip.io_adapters.for(@url) @subject = Paperclip.io_adapters.for(@url)
end end
teardown do after do
begin begin
@subject.close @subject.close
rescue Exception rescue Exception
...@@ -89,12 +89,12 @@ class HttpUrlProxyAdapterTest < Test::Unit::TestCase ...@@ -89,12 +89,12 @@ class HttpUrlProxyAdapterTest < Test::Unit::TestCase
end end
end end
should "not generate filenames that include restricted characters" do it "not generate filenames that include restricted characters" do
assert_equal "paper_clip.jpg", @subject.original_filename assert_equal "paper_clip.jpg", @subject.original_filename
end end
should "not generate paths that include restricted characters" do it "not generate paths that include restricted characters" do
assert_no_match(/:/, @subject.path) expect(@subject.path).to_not match(/:/)
end end
end end
......
require './test/helper' require 'spec_helper'
class IdentityAdapterTest < Test::Unit::TestCase describe Paperclip::IdentityAdapter do
should "respond to #new by returning the argument" do it "respond to #new by returning the argument" do
adapter = Paperclip::IdentityAdapter.new adapter = Paperclip::IdentityAdapter.new
assert_equal :target, adapter.new(:target) assert_equal :target, adapter.new(:target)
end end
......
require './test/helper' require 'spec_helper'
class NilAdapterTest < Test::Unit::TestCase describe Paperclip::NilAdapter do
context 'a new instance' do context 'a new instance' do
setup do before do
@subject = Paperclip.io_adapters.for(nil) @subject = Paperclip.io_adapters.for(nil)
end end
should "get the right filename" do it "get the right filename" do
assert_equal "", @subject.original_filename assert_equal "", @subject.original_filename
end end
should "get the content type" do it "get the content type" do
assert_equal "", @subject.content_type assert_equal "", @subject.content_type
end end
should "get the file's size" do it "get the file's size" do
assert_equal 0, @subject.size assert_equal 0, @subject.size
end end
should "return true for a call to nil?" do it "return true for a call to nil?" do
assert @subject.nil? assert @subject.nil?
end end
end end
......
require './test/helper' require 'spec_helper'
class AdapterRegistryTest < Test::Unit::TestCase describe Paperclip::AttachmentRegistry do
context "for" do context "for" do
setup do before do
class AdapterTest class AdapterTest
def initialize(target); end def initialize(target); end
end end
@subject = Paperclip::AdapterRegistry.new @subject = Paperclip::AdapterRegistry.new
@subject.register(AdapterTest){|t| Symbol === t } @subject.register(AdapterTest){|t| Symbol === t }
end end
should "return the class registered for the adapted type" do
it "return the class registered for the adapted type" do
assert_equal AdapterTest, @subject.for(:target).class assert_equal AdapterTest, @subject.for(:target).class
end end
end end
context "registered?" do context "registered?" do
setup do before do
class AdapterTest class AdapterTest
def initialize(target); end def initialize(target); end
end end
@subject = Paperclip::AdapterRegistry.new @subject = Paperclip::AdapterRegistry.new
@subject.register(AdapterTest){|t| Symbol === t } @subject.register(AdapterTest){|t| Symbol === t }
end end
should "return true when the class of this adapter has been registered" do
it "return true when the class of this adapter has been registered" do
assert @subject.registered?(AdapterTest.new(:target)) assert @subject.registered?(AdapterTest.new(:target))
end end
should "return false when the adapter has not been registered" do
it "return false when the adapter has not been registered" do
assert ! @subject.registered?(Object) assert ! @subject.registered?(Object)
end end
end end
......
require './test/helper' require 'spec_helper'
class StringioFileProxyTest < Test::Unit::TestCase describe Paperclip::StringioAdapter do
context "a new instance" do context "a new instance" do
setup do before do
@contents = "abc123" @contents = "abc123"
@stringio = StringIO.new(@contents) @stringio = StringIO.new(@contents)
@subject = Paperclip.io_adapters.for(@stringio) @subject = Paperclip.io_adapters.for(@stringio)
end end
should "return a file name" do it "return a file name" do
assert_equal "data.txt", @subject.original_filename assert_equal "data.txt", @subject.original_filename
end end
should "return a content type" do it "return a content type" do
assert_equal "text/plain", @subject.content_type assert_equal "text/plain", @subject.content_type
end end
should "return the size of the data" do it "return the size of the data" do
assert_equal 6, @subject.size assert_equal 6, @subject.size
end end
should "generate an MD5 hash of the contents" do it "generate an MD5 hash of the contents" do
assert_equal Digest::MD5.hexdigest(@contents), @subject.fingerprint assert_equal Digest::MD5.hexdigest(@contents), @subject.fingerprint
end end
should "generate correct fingerprint after read" do it "generate correct fingerprint after read" do
fingerprint = Digest::MD5.hexdigest(@subject.read) fingerprint = Digest::MD5.hexdigest(@subject.read)
assert_equal fingerprint, @subject.fingerprint assert_equal fingerprint, @subject.fingerprint
end end
should "generate same fingerprint" do it "generate same fingerprint" do
assert_equal @subject.fingerprint, @subject.fingerprint assert_equal @subject.fingerprint, @subject.fingerprint
end end
should "return the data contained in the StringIO" do it "return the data contained in the StringIO" do
assert_equal "abc123", @subject.read assert_equal "abc123", @subject.read
end end
should 'accept a content_type' do it 'accept a content_type' do
@subject.content_type = 'image/png' @subject.content_type = 'image/png'
assert_equal 'image/png', @subject.content_type assert_equal 'image/png', @subject.content_type
end end
should 'accept an original_filename' do it 'accept an original_filename' do
@subject.original_filename = 'image.png' @subject.original_filename = 'image.png'
assert_equal 'image.png', @subject.original_filename assert_equal 'image.png', @subject.original_filename
end end
should "not generate filenames that include restricted characters" do it "not generate filenames that include restricted characters" do
@subject.original_filename = 'image:restricted.png' @subject.original_filename = 'image:restricted.png'
assert_equal 'image_restricted.png', @subject.original_filename assert_equal 'image_restricted.png', @subject.original_filename
end end
should "not generate paths that include restricted characters" do it "not generate paths that include restricted characters" do
@subject.original_filename = 'image:restricted.png' @subject.original_filename = 'image:restricted.png'
assert_no_match /:/, @subject.path expect(@subject.path).to_not match(/:/)
end end
end end
......
require './test/helper' require 'spec_helper'
class UploadedFileAdapterTest < Test::Unit::TestCase describe Paperclip::UploadedFileAdapter do
context "a new instance" do context "a new instance" do
context "with UploadedFile responding to #tempfile" do context "with UploadedFile responding to #tempfile" do
setup do before do
Paperclip::UploadedFileAdapter.content_type_detector = nil Paperclip::UploadedFileAdapter.content_type_detector = nil
class UploadedFile < OpenStruct; end class UploadedFile < OpenStruct; end
...@@ -20,32 +20,32 @@ class UploadedFileAdapterTest < Test::Unit::TestCase ...@@ -20,32 +20,32 @@ class UploadedFileAdapterTest < Test::Unit::TestCase
@subject = Paperclip.io_adapters.for(@file) @subject = Paperclip.io_adapters.for(@file)
end end
should "get the right filename" do it "get the right filename" do
assert_equal "5k.png", @subject.original_filename assert_equal "5k.png", @subject.original_filename
end end
should "force binmode on tempfile" do it "force binmode on tempfile" do
assert @subject.instance_variable_get("@tempfile").binmode? assert @subject.instance_variable_get("@tempfile").binmode?
end end
should "get the content type" do it "get the content type" do
assert_equal "image/x-png-by-browser", @subject.content_type assert_equal "image/x-png-by-browser", @subject.content_type
end end
should "get the file's size" do it "get the file's size" do
assert_equal 4456, @subject.size assert_equal 4456, @subject.size
end end
should "return false for a call to nil?" do it "return false for a call to nil?" do
assert ! @subject.nil? assert ! @subject.nil?
end end
should "generate a MD5 hash of the contents" do it "generate a MD5 hash of the contents" do
expected = Digest::MD5.file(@file.tempfile.path).to_s expected = Digest::MD5.file(@file.tempfile.path).to_s
assert_equal expected, @subject.fingerprint assert_equal expected, @subject.fingerprint
end end
should "read the contents of the file" do it "read the contents of the file" do
expected = @file.tempfile.read expected = @file.tempfile.read
assert expected.length > 0 assert expected.length > 0
assert_equal expected, @subject.read assert_equal expected, @subject.read
...@@ -53,7 +53,7 @@ class UploadedFileAdapterTest < Test::Unit::TestCase ...@@ -53,7 +53,7 @@ class UploadedFileAdapterTest < Test::Unit::TestCase
end end
context "with UploadedFile that has restricted characters" do context "with UploadedFile that has restricted characters" do
setup do before do
Paperclip::UploadedFileAdapter.content_type_detector = nil Paperclip::UploadedFileAdapter.content_type_detector = nil
class UploadedFile < OpenStruct; end class UploadedFile < OpenStruct; end
...@@ -66,17 +66,17 @@ class UploadedFileAdapterTest < Test::Unit::TestCase ...@@ -66,17 +66,17 @@ class UploadedFileAdapterTest < Test::Unit::TestCase
@subject = Paperclip.io_adapters.for(@file) @subject = Paperclip.io_adapters.for(@file)
end end
should "not generate paths that include restricted characters" do it "not generate paths that include restricted characters" do
assert_no_match /:/, @subject.path expect(@subject.path).to_not match(/:/)
end end
should "not generate filenames that include restricted characters" do it "not generate filenames that include restricted characters" do
assert_equal 'image_restricted.gif', @subject.original_filename assert_equal 'image_restricted.gif', @subject.original_filename
end end
end end
context "with UploadFile responding to #path" do context "with UploadFile responding to #path" do
setup do before do
Paperclip::UploadedFileAdapter.content_type_detector = nil Paperclip::UploadedFileAdapter.content_type_detector = nil
class UploadedFile < OpenStruct; end class UploadedFile < OpenStruct; end
...@@ -89,32 +89,32 @@ class UploadedFileAdapterTest < Test::Unit::TestCase ...@@ -89,32 +89,32 @@ class UploadedFileAdapterTest < Test::Unit::TestCase
@subject = Paperclip.io_adapters.for(@file) @subject = Paperclip.io_adapters.for(@file)
end end
should "get the right filename" do it "get the right filename" do
assert_equal "5k.png", @subject.original_filename assert_equal "5k.png", @subject.original_filename
end end
should "force binmode on tempfile" do it "force binmode on tempfile" do
assert @subject.instance_variable_get("@tempfile").binmode? assert @subject.instance_variable_get("@tempfile").binmode?
end end
should "get the content type" do it "get the content type" do
assert_equal "image/x-png-by-browser", @subject.content_type assert_equal "image/x-png-by-browser", @subject.content_type
end end
should "get the file's size" do it "get the file's size" do
assert_equal 4456, @subject.size assert_equal 4456, @subject.size
end end
should "return false for a call to nil?" do it "return false for a call to nil?" do
assert ! @subject.nil? assert ! @subject.nil?
end end
should "generate a MD5 hash of the contents" do it "generate a MD5 hash of the contents" do
expected = Digest::MD5.file(@file.path).to_s expected = Digest::MD5.file(@file.path).to_s
assert_equal expected, @subject.fingerprint assert_equal expected, @subject.fingerprint
end end
should "read the contents of the file" do it "read the contents of the file" do
expected_file = File.new(@file.path) expected_file = File.new(@file.path)
expected_file.binmode expected_file.binmode
expected = expected_file.read expected = expected_file.read
...@@ -123,7 +123,7 @@ class UploadedFileAdapterTest < Test::Unit::TestCase ...@@ -123,7 +123,7 @@ class UploadedFileAdapterTest < Test::Unit::TestCase
end end
context "don't trust client-given MIME type" do context "don't trust client-given MIME type" do
setup do before do
Paperclip::UploadedFileAdapter.content_type_detector = Paperclip::UploadedFileAdapter.content_type_detector =
Paperclip::FileCommandContentTypeDetector Paperclip::FileCommandContentTypeDetector
...@@ -137,7 +137,7 @@ class UploadedFileAdapterTest < Test::Unit::TestCase ...@@ -137,7 +137,7 @@ class UploadedFileAdapterTest < Test::Unit::TestCase
@subject = Paperclip.io_adapters.for(@file) @subject = Paperclip.io_adapters.for(@file)
end end
should "get the content type" do it "get the content type" do
assert_equal "image/png", @subject.content_type assert_equal "image/png", @subject.content_type
end end
end end
......
require './test/helper' require 'spec_helper'
class UriProxyTest < Test::Unit::TestCase describe Paperclip::UriAdapter do
context "a new instance" do context "a new instance" do
setup do before do
@open_return = StringIO.new("xxx") @open_return = StringIO.new("xxx")
@open_return.stubs(:content_type).returns("image/png") @open_return.stubs(:content_type).returns("image/png")
Paperclip::UriAdapter.any_instance.stubs(:download_content).returns(@open_return) Paperclip::UriAdapter.any_instance.stubs(:download_content).returns(@open_return)
...@@ -10,45 +10,45 @@ class UriProxyTest < Test::Unit::TestCase ...@@ -10,45 +10,45 @@ class UriProxyTest < Test::Unit::TestCase
@subject = Paperclip.io_adapters.for(@uri) @subject = Paperclip.io_adapters.for(@uri)
end end
should "return a file name" do it "return a file name" do
assert_equal "thoughtbot-logo.png", @subject.original_filename assert_equal "thoughtbot-logo.png", @subject.original_filename
end end
should 'close open handle after reading' do it 'close open handle after reading' do
assert_equal true, @open_return.closed? assert_equal true, @open_return.closed?
end end
should "return a content type" do it "return a content type" do
assert_equal "image/png", @subject.content_type assert_equal "image/png", @subject.content_type
end end
should "return the size of the data" do it "return the size of the data" do
assert_equal @open_return.size, @subject.size assert_equal @open_return.size, @subject.size
end end
should "generate an MD5 hash of the contents" do it "generate an MD5 hash of the contents" do
assert_equal Digest::MD5.hexdigest("xxx"), @subject.fingerprint assert_equal Digest::MD5.hexdigest("xxx"), @subject.fingerprint
end end
should "generate correct fingerprint after read" do it "generate correct fingerprint after read" do
fingerprint = Digest::MD5.hexdigest(@subject.read) fingerprint = Digest::MD5.hexdigest(@subject.read)
assert_equal fingerprint, @subject.fingerprint assert_equal fingerprint, @subject.fingerprint
end end
should "generate same fingerprint" do it "generate same fingerprint" do
assert_equal @subject.fingerprint, @subject.fingerprint assert_equal @subject.fingerprint, @subject.fingerprint
end end
should "return the data contained in the StringIO" do it "return the data contained in the StringIO" do
assert_equal "xxx", @subject.read assert_equal "xxx", @subject.read
end end
should 'accept a content_type' do it 'accept a content_type' do
@subject.content_type = 'image/png' @subject.content_type = 'image/png'
assert_equal 'image/png', @subject.content_type assert_equal 'image/png', @subject.content_type
end end
should 'accept an orgiginal_filename' do it 'accept an orgiginal_filename' do
@subject.original_filename = 'image.png' @subject.original_filename = 'image.png'
assert_equal 'image.png', @subject.original_filename assert_equal 'image.png', @subject.original_filename
end end
...@@ -56,46 +56,46 @@ class UriProxyTest < Test::Unit::TestCase ...@@ -56,46 +56,46 @@ class UriProxyTest < Test::Unit::TestCase
end end
context "a directory index url" do context "a directory index url" do
setup do before do
Paperclip::UriAdapter.any_instance.stubs(:download_content).returns(StringIO.new("xxx")) Paperclip::UriAdapter.any_instance.stubs(:download_content).returns(StringIO.new("xxx"))
@uri = URI.parse("http://thoughtbot.com") @uri = URI.parse("http://thoughtbot.com")
@subject = Paperclip.io_adapters.for(@uri) @subject = Paperclip.io_adapters.for(@uri)
end end
should "return a file name" do it "return a file name" do
assert_equal "index.html", @subject.original_filename assert_equal "index.html", @subject.original_filename
end end
should "return a content type" do it "return a content type" do
assert_equal "text/html", @subject.content_type assert_equal "text/html", @subject.content_type
end end
end end
context "a url with query params" do context "a url with query params" do
setup do before do
Paperclip::UriAdapter.any_instance.stubs(:download_content).returns(StringIO.new("xxx")) Paperclip::UriAdapter.any_instance.stubs(:download_content).returns(StringIO.new("xxx"))
@uri = URI.parse("https://github.com/thoughtbot/paperclip?file=test") @uri = URI.parse("https://github.com/thoughtbot/paperclip?file=test")
@subject = Paperclip.io_adapters.for(@uri) @subject = Paperclip.io_adapters.for(@uri)
end end
should "return a file name" do it "return a file name" do
assert_equal "paperclip", @subject.original_filename assert_equal "paperclip", @subject.original_filename
end end
end end
context "a url with restricted characters in the filename" do context "a url with restricted characters in the filename" do
setup do before do
Paperclip::UriAdapter.any_instance.stubs(:download_content).returns(StringIO.new("xxx")) Paperclip::UriAdapter.any_instance.stubs(:download_content).returns(StringIO.new("xxx"))
@uri = URI.parse("https://github.com/thoughtbot/paper:clip.jpg") @uri = URI.parse("https://github.com/thoughtbot/paper:clip.jpg")
@subject = Paperclip.io_adapters.for(@uri) @subject = Paperclip.io_adapters.for(@uri)
end end
should "not generate filenames that include restricted characters" do it "not generate filenames that include restricted characters" do
assert_equal "paper_clip.jpg", @subject.original_filename assert_equal "paper_clip.jpg", @subject.original_filename
end end
should "not generate paths that include restricted characters" do it "not generate paths that include restricted characters" do
assert_no_match /:/, @subject.path expect(@subject.path).to_not match(/:/)
end end
end end
......
require 'spec_helper'
require 'paperclip/matchers'
describe Paperclip::Shoulda::Matchers::HaveAttachedFileMatcher do
extend Paperclip::Shoulda::Matchers
it "rejects the dummy class if it has no attachment" do
reset_table "dummies"
reset_class "Dummy"
matcher = self.class.have_attached_file(:avatar)
expect(matcher).to_not accept(Dummy)
end
it 'accepts the dummy class if it has an attachment' do
rebuild_model
matcher = self.class.have_attached_file(:avatar)
expect(matcher).to accept(Dummy)
end
end
require './test/helper' require 'spec_helper'
require 'paperclip/matchers'
describe Paperclip::Shoulda::Matchers::ValidateAttachmentContentTypeMatcher do
extend Paperclip::Shoulda::Matchers
class ValidateAttachmentContentTypeMatcherTest < Test::Unit::TestCase
context "validate_attachment_content_type" do context "validate_attachment_content_type" do
setup do before do
reset_table("dummies") do |d| reset_table("dummies") do |d|
d.string :title d.string :title
d.string :avatar_file_name d.string :avatar_file_name
...@@ -21,7 +24,7 @@ class ValidateAttachmentContentTypeMatcherTest < Test::Unit::TestCase ...@@ -21,7 +24,7 @@ class ValidateAttachmentContentTypeMatcherTest < Test::Unit::TestCase
end end
context "given a class with a validation that doesn't match" do context "given a class with a validation that doesn't match" do
setup do before do
Dummy.validates_attachment_content_type :avatar, :content_type => %r{audio/.*} Dummy.validates_attachment_content_type :avatar, :content_type => %r{audio/.*}
end end
...@@ -29,7 +32,7 @@ class ValidateAttachmentContentTypeMatcherTest < Test::Unit::TestCase ...@@ -29,7 +32,7 @@ class ValidateAttachmentContentTypeMatcherTest < Test::Unit::TestCase
end end
context "given a class with a matching validation" do context "given a class with a matching validation" do
setup do before do
Dummy.validates_attachment_content_type :avatar, :content_type => %r{image/.*} Dummy.validates_attachment_content_type :avatar, :content_type => %r{image/.*}
end end
...@@ -37,7 +40,7 @@ class ValidateAttachmentContentTypeMatcherTest < Test::Unit::TestCase ...@@ -37,7 +40,7 @@ class ValidateAttachmentContentTypeMatcherTest < Test::Unit::TestCase
end end
context "given a class with other validations but matching types" do context "given a class with other validations but matching types" do
setup do before do
Dummy.validates_presence_of :title Dummy.validates_presence_of :title
Dummy.validates_attachment_content_type :avatar, :content_type => %r{image/.*} Dummy.validates_attachment_content_type :avatar, :content_type => %r{image/.*}
end end
...@@ -46,7 +49,7 @@ class ValidateAttachmentContentTypeMatcherTest < Test::Unit::TestCase ...@@ -46,7 +49,7 @@ class ValidateAttachmentContentTypeMatcherTest < Test::Unit::TestCase
end end
context "given a class that matches and a matcher that only specifies 'allowing'" do context "given a class that matches and a matcher that only specifies 'allowing'" do
setup do before do
Dummy.validates_attachment_content_type :avatar, :content_type => %r{image/.*} Dummy.validates_attachment_content_type :avatar, :content_type => %r{image/.*}
@matcher = self.class.validate_attachment_content_type(:avatar). @matcher = self.class.validate_attachment_content_type(:avatar).
allowing(%w(image/png image/jpeg)) allowing(%w(image/png image/jpeg))
...@@ -56,7 +59,7 @@ class ValidateAttachmentContentTypeMatcherTest < Test::Unit::TestCase ...@@ -56,7 +59,7 @@ class ValidateAttachmentContentTypeMatcherTest < Test::Unit::TestCase
end end
context "given a class that does not match and a matcher that only specifies 'allowing'" do context "given a class that does not match and a matcher that only specifies 'allowing'" do
setup do before do
Dummy.validates_attachment_content_type :avatar, :content_type => %r{audio/.*} Dummy.validates_attachment_content_type :avatar, :content_type => %r{audio/.*}
@matcher = self.class.validate_attachment_content_type(:avatar). @matcher = self.class.validate_attachment_content_type(:avatar).
allowing(%w(image/png image/jpeg)) allowing(%w(image/png image/jpeg))
...@@ -66,7 +69,7 @@ class ValidateAttachmentContentTypeMatcherTest < Test::Unit::TestCase ...@@ -66,7 +69,7 @@ class ValidateAttachmentContentTypeMatcherTest < Test::Unit::TestCase
end end
context "given a class that matches and a matcher that only specifies 'rejecting'" do context "given a class that matches and a matcher that only specifies 'rejecting'" do
setup do before do
Dummy.validates_attachment_content_type :avatar, :content_type => %r{image/.*} Dummy.validates_attachment_content_type :avatar, :content_type => %r{image/.*}
@matcher = self.class.validate_attachment_content_type(:avatar). @matcher = self.class.validate_attachment_content_type(:avatar).
rejecting(%w(audio/mp3 application/octet-stream)) rejecting(%w(audio/mp3 application/octet-stream))
...@@ -76,7 +79,7 @@ class ValidateAttachmentContentTypeMatcherTest < Test::Unit::TestCase ...@@ -76,7 +79,7 @@ class ValidateAttachmentContentTypeMatcherTest < Test::Unit::TestCase
end end
context "given a class that does not match and a matcher that only specifies 'rejecting'" do context "given a class that does not match and a matcher that only specifies 'rejecting'" do
setup do before do
Dummy.validates_attachment_content_type :avatar, :content_type => %r{audio/.*} Dummy.validates_attachment_content_type :avatar, :content_type => %r{audio/.*}
@matcher = self.class.validate_attachment_content_type(:avatar). @matcher = self.class.validate_attachment_content_type(:avatar).
rejecting(%w(audio/mp3 application/octet-stream)) rejecting(%w(audio/mp3 application/octet-stream))
...@@ -86,7 +89,7 @@ class ValidateAttachmentContentTypeMatcherTest < Test::Unit::TestCase ...@@ -86,7 +89,7 @@ class ValidateAttachmentContentTypeMatcherTest < Test::Unit::TestCase
end end
context "using an :if to control the validation" do context "using an :if to control the validation" do
setup do before do
Dummy.class_eval do Dummy.class_eval do
validates_attachment_content_type :avatar, :content_type => %r{image/*} , :if => :go validates_attachment_content_type :avatar, :content_type => %r{image/*} , :if => :go
attr_accessor :go attr_accessor :go
...@@ -97,14 +100,14 @@ class ValidateAttachmentContentTypeMatcherTest < Test::Unit::TestCase ...@@ -97,14 +100,14 @@ class ValidateAttachmentContentTypeMatcherTest < Test::Unit::TestCase
@dummy = Dummy.new @dummy = Dummy.new
end end
should "run the validation if the control is true" do it "run the validation if the control is true" do
@dummy.go = true @dummy.go = true
assert_accepts @matcher, @dummy expect(@matcher).to accept(@dummy)
end end
should "not run the validation if the control is false" do it "not run the validation if the control is false" do
@dummy.go = false @dummy.go = false
assert_rejects @matcher, @dummy expect(@matcher).to_not accept(@dummy)
end end
end end
end end
......
require './test/helper' require 'spec_helper'
require 'paperclip/matchers'
describe Paperclip::Shoulda::Matchers::ValidateAttachmentPresenceMatcher do
extend Paperclip::Shoulda::Matchers
class ValidateAttachmentPresenceMatcherTest < Test::Unit::TestCase
context "validate_attachment_presence" do context "validate_attachment_presence" do
setup do before do
reset_table("dummies") do |d| reset_table("dummies") do |d|
d.string :avatar_file_name d.string :avatar_file_name
end end
...@@ -17,7 +20,7 @@ class ValidateAttachmentPresenceMatcherTest < Test::Unit::TestCase ...@@ -17,7 +20,7 @@ class ValidateAttachmentPresenceMatcherTest < Test::Unit::TestCase
end end
context "given a class with a matching validation" do context "given a class with a matching validation" do
setup do before do
Dummy.validates_attachment_presence :avatar Dummy.validates_attachment_presence :avatar
end end
...@@ -25,7 +28,7 @@ class ValidateAttachmentPresenceMatcherTest < Test::Unit::TestCase ...@@ -25,7 +28,7 @@ class ValidateAttachmentPresenceMatcherTest < Test::Unit::TestCase
end end
context "given an instance with other attachment validations" do context "given an instance with other attachment validations" do
setup do before do
reset_table("dummies") do |d| reset_table("dummies") do |d|
d.string :avatar_file_name d.string :avatar_file_name
d.string :avatar_content_type d.string :avatar_content_type
...@@ -40,14 +43,14 @@ class ValidateAttachmentPresenceMatcherTest < Test::Unit::TestCase ...@@ -40,14 +43,14 @@ class ValidateAttachmentPresenceMatcherTest < Test::Unit::TestCase
@matcher = self.class.validate_attachment_presence(:avatar) @matcher = self.class.validate_attachment_presence(:avatar)
end end
should "it should validate properly" do it "it should validate properly" do
@dummy.avatar = File.new fixture_file('5k.png') @dummy.avatar = File.new fixture_file('5k.png')
assert_accepts @matcher, @dummy expect(@matcher).to accept(@dummy)
end end
end end
context "using an :if to control the validation" do context "using an :if to control the validation" do
setup do before do
Dummy.class_eval do Dummy.class_eval do
validates_attachment_presence :avatar, :if => :go validates_attachment_presence :avatar, :if => :go
attr_accessor :go attr_accessor :go
...@@ -56,14 +59,14 @@ class ValidateAttachmentPresenceMatcherTest < Test::Unit::TestCase ...@@ -56,14 +59,14 @@ class ValidateAttachmentPresenceMatcherTest < Test::Unit::TestCase
@dummy.avatar = nil @dummy.avatar = nil
end end
should "run the validation if the control is true" do it "run the validation if the control is true" do
@dummy.go = true @dummy.go = true
assert_accepts @matcher, @dummy expect(@matcher).to accept(@dummy)
end end
should "not run the validation if the control is false" do it "not run the validation if the control is false" do
@dummy.go = false @dummy.go = false
assert_rejects @matcher, @dummy expect(@matcher).to_not accept(@dummy)
end end
end end
end end
......
require './test/helper' require 'spec_helper'
require 'paperclip/matchers'
describe Paperclip::Shoulda::Matchers::ValidateAttachmentSizeMatcher do
extend Paperclip::Shoulda::Matchers
class ValidateAttachmentSizeMatcherTest < Test::Unit::TestCase
context "validate_attachment_size" do context "validate_attachment_size" do
setup do before do
reset_table("dummies") do |d| reset_table("dummies") do |d|
d.string :avatar_file_name d.string :avatar_file_name
d.integer :avatar_file_size d.integer :avatar_file_size
...@@ -13,44 +16,48 @@ class ValidateAttachmentSizeMatcherTest < Test::Unit::TestCase ...@@ -13,44 +16,48 @@ class ValidateAttachmentSizeMatcherTest < Test::Unit::TestCase
end end
context "of limited size" do context "of limited size" do
setup{ @matcher = self.class.validate_attachment_size(:avatar).in(256..1024) } before do
@matcher = self.class.validate_attachment_size(:avatar).in(256..1024)
end
context "given a class with no validation" do context "given a class with no validation" do
should_reject_dummy_class should_reject_dummy_class
end end
context "given a class with a validation that's too high" do context "given a class with a validation that's too high" do
setup { Dummy.validates_attachment_size :avatar, :in => 256..2048 } before { Dummy.validates_attachment_size :avatar, :in => 256..2048 }
should_reject_dummy_class should_reject_dummy_class
end end
context "given a class with a validation that's too low" do context "given a class with a validation that's too low" do
setup { Dummy.validates_attachment_size :avatar, :in => 0..1024 } before { Dummy.validates_attachment_size :avatar, :in => 0..1024 }
should_reject_dummy_class should_reject_dummy_class
end end
context "given a class with a validation that matches" do context "given a class with a validation that matches" do
setup { Dummy.validates_attachment_size :avatar, :in => 256..1024 } before { Dummy.validates_attachment_size :avatar, :in => 256..1024 }
should_accept_dummy_class should_accept_dummy_class
end end
end end
context "allowing anything" do context "allowing anything" do
setup{ @matcher = self.class.validate_attachment_size(:avatar) } before do
@matcher = self.class.validate_attachment_size(:avatar)
end
context "given a class with an upper limit" do context "given a class with an upper limit" do
setup { Dummy.validates_attachment_size :avatar, :less_than => 1 } before { Dummy.validates_attachment_size :avatar, :less_than => 1 }
should_accept_dummy_class should_accept_dummy_class
end end
context "given a class with a lower limit" do context "given a class with a lower limit" do
setup { Dummy.validates_attachment_size :avatar, :greater_than => 1 } before { Dummy.validates_attachment_size :avatar, :greater_than => 1 }
should_accept_dummy_class should_accept_dummy_class
end end
end end
context "using an :if to control the validation" do context "using an :if to control the validation" do
setup do before do
Dummy.class_eval do Dummy.class_eval do
validates_attachment_size :avatar, :greater_than => 1024, :if => :go validates_attachment_size :avatar, :greater_than => 1024, :if => :go
attr_accessor :go attr_accessor :go
...@@ -59,28 +66,28 @@ class ValidateAttachmentSizeMatcherTest < Test::Unit::TestCase ...@@ -59,28 +66,28 @@ class ValidateAttachmentSizeMatcherTest < Test::Unit::TestCase
@matcher = self.class.validate_attachment_size(:avatar).greater_than(1024) @matcher = self.class.validate_attachment_size(:avatar).greater_than(1024)
end end
should "run the validation if the control is true" do it "run the validation if the control is true" do
@dummy.go = true @dummy.go = true
assert_accepts @matcher, @dummy expect(@matcher).to accept(@dummy)
end end
should "not run the validation if the control is false" do it "not run the validation if the control is false" do
@dummy.go = false @dummy.go = false
assert_rejects @matcher, @dummy expect(@matcher).to_not accept(@dummy)
end end
end end
context "post processing" do context "post processing" do
setup do before do
Dummy.validates_attachment_size :avatar, :greater_than => 1024 Dummy.validates_attachment_size :avatar, :greater_than => 1024
@dummy = Dummy.new @dummy = Dummy.new
@matcher = self.class.validate_attachment_size(:avatar).greater_than(1024) @matcher = self.class.validate_attachment_size(:avatar).greater_than(1024)
end end
should "be skipped" do it "be skipped" do
@dummy.avatar.expects(:post_process).never @dummy.avatar.expects(:post_process).never
assert_accepts @matcher, @dummy expect(@matcher).to accept(@dummy)
end end
end end
end end
......
require './test/helper' require 'spec_helper'
class MediaTypeSpoofDetectorTest < Test::Unit::TestCase describe Paperclip::MediaTypeSpoofDetector do
should 'reject a file that is named .html and identifies as PNG' do it 'reject a file that is named .html and identifies as PNG' do
file = File.open(fixture_file("5k.png")) file = File.open(fixture_file("5k.png"))
assert Paperclip::MediaTypeSpoofDetector.using(file, "5k.html").spoofed? assert Paperclip::MediaTypeSpoofDetector.using(file, "5k.html").spoofed?
end end
should 'not reject a file that is named .jpg and identifies as PNG' do it 'not reject a file that is named .jpg and identifies as PNG' do
file = File.open(fixture_file("5k.png")) file = File.open(fixture_file("5k.png"))
assert ! Paperclip::MediaTypeSpoofDetector.using(file, "5k.jpg").spoofed? assert ! Paperclip::MediaTypeSpoofDetector.using(file, "5k.jpg").spoofed?
end end
should 'not reject a file that is named .html and identifies as HTML' do it 'not reject a file that is named .html and identifies as HTML' do
file = File.open(fixture_file("empty.html")) file = File.open(fixture_file("empty.html"))
assert ! Paperclip::MediaTypeSpoofDetector.using(file, "empty.html").spoofed? assert ! Paperclip::MediaTypeSpoofDetector.using(file, "empty.html").spoofed?
end end
should 'not reject a file that does not have a name' do it 'not reject a file that does not have a name' do
file = File.open(fixture_file("empty.html")) file = File.open(fixture_file("empty.html"))
assert ! Paperclip::MediaTypeSpoofDetector.using(file, "").spoofed? assert ! Paperclip::MediaTypeSpoofDetector.using(file, "").spoofed?
end end
should 'not reject when the supplied file is an IOAdapter' do it 'not reject when the supplied file is an IOAdapter' do
adapter = Paperclip.io_adapters.for(File.new(fixture_file("5k.png"))) adapter = Paperclip.io_adapters.for(File.new(fixture_file("5k.png")))
assert ! Paperclip::MediaTypeSpoofDetector.using(adapter, adapter.original_filename).spoofed? assert ! Paperclip::MediaTypeSpoofDetector.using(adapter, adapter.original_filename).spoofed?
end end
should 'not reject when the extension => content_type is in :content_type_mappings' do it 'not reject when the extension => content_type is in :content_type_mappings' do
begin begin
Paperclip.options[:content_type_mappings] = { pem: "text/plain" } Paperclip.options[:content_type_mappings] = { pem: "text/plain" }
file = Tempfile.open(["test", ".PEM"]) file = Tempfile.open(["test", ".PEM"])
......
require './test/helper' require 'spec_helper'
class MetaClassTest < Test::Unit::TestCase describe 'Metaclasses' do
context "A meta-class of dummy" do context "A meta-class of dummy" do
setup do before do
rebuild_model rebuild_model("Dummy")
@file = File.new(fixture_file("5k.png"), 'rb') reset_class("Dummy")
end end
teardown { @file.close } it "be able to use Paperclip like a normal class" do
should "be able to use Paperclip like a normal class" do
reset_class("Dummy")
@dummy = Dummy.new @dummy = Dummy.new
assert_nothing_raised do assert_nothing_raised do
...@@ -18,13 +15,12 @@ class MetaClassTest < Test::Unit::TestCase ...@@ -18,13 +15,12 @@ class MetaClassTest < Test::Unit::TestCase
end end
end end
should "work like any other instance" do it "work like any other instance" do
reset_class("Dummy")
@dummy = Dummy.new @dummy = Dummy.new
rebuild_meta_class_of(@dummy) rebuild_meta_class_of(@dummy)
assert_nothing_raised do assert_nothing_raised do
@dummy.avatar = @file @dummy.avatar = File.new(fixture_file("5k.png"), 'rb')
end end
assert @dummy.save assert @dummy.save
end end
......
require './test/helper' require 'spec_helper'
class PaperclipMissingAttachmentStylesTest < Test::Unit::TestCase describe 'Missing Attachment Styles' do
def setup before do
Paperclip::AttachmentRegistry.clear Paperclip::AttachmentRegistry.clear
end end
context "Paperclip" do after do
setup do File.unlink(Paperclip.registered_attachments_styles_path) rescue nil
Paperclip::AttachmentRegistry.clear end
end
teardown do
File.unlink(Paperclip.registered_attachments_styles_path) rescue nil
end
should "enable to get and set path to registered styles file" do
assert_equal ROOT.join('tmp/public/system/paperclip_attachments.yml').to_s, Paperclip.registered_attachments_styles_path
Paperclip.registered_attachments_styles_path = '/tmp/config/paperclip_attachments.yml'
assert_equal '/tmp/config/paperclip_attachments.yml', Paperclip.registered_attachments_styles_path
Paperclip.registered_attachments_styles_path = nil
assert_equal ROOT.join('tmp/public/system/paperclip_attachments.yml').to_s, Paperclip.registered_attachments_styles_path
end
should "be able to get current attachment styles" do it "enable to get and set path to registered styles file" do
assert_equal Hash.new, Paperclip.send(:current_attachments_styles) assert_equal ROOT.join('tmp/public/system/paperclip_attachments.yml').to_s, Paperclip.registered_attachments_styles_path
rebuild_model :styles => {:croppable => '600x600>', :big => '1000x1000>'} Paperclip.registered_attachments_styles_path = '/tmp/config/paperclip_attachments.yml'
expected_hash = { :Dummy => {:avatar => [:big, :croppable]}} assert_equal '/tmp/config/paperclip_attachments.yml', Paperclip.registered_attachments_styles_path
assert_equal expected_hash, Paperclip.send(:current_attachments_styles) Paperclip.registered_attachments_styles_path = nil
end assert_equal ROOT.join('tmp/public/system/paperclip_attachments.yml').to_s, Paperclip.registered_attachments_styles_path
end
should "be able to save current attachment styles for further comparison" do it "be able to get current attachment styles" do
rebuild_model :styles => {:croppable => '600x600>', :big => '1000x1000>'} assert_equal Hash.new, Paperclip.send(:current_attachments_styles)
Paperclip.save_current_attachments_styles! rebuild_model :styles => {:croppable => '600x600>', :big => '1000x1000>'}
expected_hash = { :Dummy => {:avatar => [:big, :croppable]}} expected_hash = { :Dummy => {:avatar => [:big, :croppable]}}
assert_equal expected_hash, YAML.load_file(Paperclip.registered_attachments_styles_path) assert_equal expected_hash, Paperclip.send(:current_attachments_styles)
end end
should "be able to read registered attachment styles from file" do it "be able to save current attachment styles for further comparison" do
rebuild_model :styles => {:croppable => '600x600>', :big => '1000x1000>'} rebuild_model :styles => {:croppable => '600x600>', :big => '1000x1000>'}
Paperclip.save_current_attachments_styles! Paperclip.save_current_attachments_styles!
expected_hash = { :Dummy => {:avatar => [:big, :croppable]}} expected_hash = { :Dummy => {:avatar => [:big, :croppable]}}
assert_equal expected_hash, Paperclip.send(:get_registered_attachments_styles) assert_equal expected_hash, YAML.load_file(Paperclip.registered_attachments_styles_path)
end end
should "be able to calculate differences between registered styles and current styles" do it "be able to read registered attachment styles from file" do
rebuild_model :styles => {:croppable => '600x600>', :big => '1000x1000>'} rebuild_model :styles => {:croppable => '600x600>', :big => '1000x1000>'}
Paperclip.save_current_attachments_styles! Paperclip.save_current_attachments_styles!
rebuild_model :styles => {:thumb => 'x100', :export => 'x400>', :croppable => '600x600>', :big => '1000x1000>'} expected_hash = { :Dummy => {:avatar => [:big, :croppable]}}
expected_hash = { :Dummy => {:avatar => [:export, :thumb]} } assert_equal expected_hash, Paperclip.send(:get_registered_attachments_styles)
assert_equal expected_hash, Paperclip.missing_attachments_styles end
ActiveRecord::Base.connection.create_table :books, :force => true it "be able to calculate differences between registered styles and current styles" do
class ::Book < ActiveRecord::Base rebuild_model :styles => {:croppable => '600x600>', :big => '1000x1000>'}
has_attached_file :cover, :styles => {:small => 'x100', :large => '1000x1000>'} Paperclip.save_current_attachments_styles!
has_attached_file :sample, :styles => {:thumb => 'x100'} rebuild_model :styles => {:thumb => 'x100', :export => 'x400>', :croppable => '600x600>', :big => '1000x1000>'}
end expected_hash = { :Dummy => {:avatar => [:export, :thumb]} }
assert_equal expected_hash, Paperclip.missing_attachments_styles
expected_hash = { ActiveRecord::Base.connection.create_table :books, :force => true
:Dummy => {:avatar => [:export, :thumb]}, class ::Book < ActiveRecord::Base
:Book => {:sample => [:thumb], :cover => [:large, :small]} has_attached_file :cover, :styles => {:small => 'x100', :large => '1000x1000>'}
} has_attached_file :sample, :styles => {:thumb => 'x100'}
assert_equal expected_hash, Paperclip.missing_attachments_styles
Paperclip.save_current_attachments_styles!
assert_equal Hash.new, Paperclip.missing_attachments_styles
end end
should "be able to calculate differences when a new attachment is added to a model" do expected_hash = {
rebuild_model :styles => {:croppable => '600x600>', :big => '1000x1000>'} :Dummy => {:avatar => [:export, :thumb]},
Paperclip.save_current_attachments_styles! :Book => {:sample => [:thumb], :cover => [:large, :small]}
}
assert_equal expected_hash, Paperclip.missing_attachments_styles
Paperclip.save_current_attachments_styles!
assert_equal Hash.new, Paperclip.missing_attachments_styles
end
class ::Dummy it "be able to calculate differences when a new attachment is added to a model" do
has_attached_file :photo, :styles => {:small => 'x100', :large => '1000x1000>'} rebuild_model :styles => {:croppable => '600x600>', :big => '1000x1000>'}
end Paperclip.save_current_attachments_styles!
expected_hash = { class ::Dummy
:Dummy => {:photo => [:large, :small]} has_attached_file :photo, :styles => {:small => 'x100', :large => '1000x1000>'}
}
assert_equal expected_hash, Paperclip.missing_attachments_styles
Paperclip.save_current_attachments_styles!
assert_equal Hash.new, Paperclip.missing_attachments_styles
end end
# It's impossible to build styles hash without loading from database whole bunch of records expected_hash = {
should "skip lambda-styles" do :Dummy => {:photo => [:large, :small]}
rebuild_model :styles => lambda{ |attachment| attachment.instance.other == 'a' ? {:thumb => "50x50#"} : {:large => "400x400"} } }
assert_equal Hash.new, Paperclip.send(:current_attachments_styles) assert_equal expected_hash, Paperclip.missing_attachments_styles
end Paperclip.save_current_attachments_styles!
assert_equal Hash.new, Paperclip.missing_attachments_styles
end
# It's impossible to build styles hash without loading from database whole bunch of records
it "skip lambda-styles" do
rebuild_model :styles => lambda{ |attachment| attachment.instance.other == 'a' ? {:thumb => "50x50#"} : {:large => "400x400"} }
assert_equal Hash.new, Paperclip.send(:current_attachments_styles)
end end
end end
require './test/helper' require 'spec_helper'
class PaperclipTest < Test::Unit::TestCase describe Paperclip do
context "Calling Paperclip.run" do context ".run" do
setup do before do
Paperclip.options[:log_command] = false Paperclip.options[:log_command] = false
Cocaine::CommandLine.expects(:new).with("convert", "stuff", {}).returns(stub(:run)) Cocaine::CommandLine.expects(:new).with("convert", "stuff", {}).returns(stub(:run))
@original_command_line_path = Cocaine::CommandLine.path @original_command_line_path = Cocaine::CommandLine.path
end end
teardown do after do
Paperclip.options[:log_command] = true Paperclip.options[:log_command] = true
Cocaine::CommandLine.path = @original_command_line_path Cocaine::CommandLine.path = @original_command_line_path
end end
should "run the command with Cocaine" do it "run the command with Cocaine" do
Paperclip.run("convert", "stuff") Paperclip.run("convert", "stuff")
end end
should "save Cocaine::CommandLine.path that set before" do it "save Cocaine::CommandLine.path that set before" do
Cocaine::CommandLine.path = "/opt/my_app/bin" Cocaine::CommandLine.path = "/opt/my_app/bin"
Paperclip.run("convert", "stuff") Paperclip.run("convert", "stuff")
assert_equal [Cocaine::CommandLine.path].flatten.include?("/opt/my_app/bin"), true assert_equal [Cocaine::CommandLine.path].flatten.include?("/opt/my_app/bin"), true
end end
should "not duplicate Cocaine::CommandLine.path on multiple runs" do it "not duplicate Cocaine::CommandLine.path on multiple runs" do
Cocaine::CommandLine.expects(:new).with("convert", "more_stuff", {}).returns(stub(:run)) Cocaine::CommandLine.expects(:new).with("convert", "more_stuff", {}).returns(stub(:run))
Cocaine::CommandLine.path = nil Cocaine::CommandLine.path = nil
Paperclip.options[:command_path] = "/opt/my_app/bin" Paperclip.options[:command_path] = "/opt/my_app/bin"
...@@ -33,7 +33,7 @@ class PaperclipTest < Test::Unit::TestCase ...@@ -33,7 +33,7 @@ class PaperclipTest < Test::Unit::TestCase
end end
end end
should 'not raise errors when doing a lot of running' do it 'not raise errors when doing a lot of running' do
Paperclip.options[:command_path] = ["/usr/local/bin"] * 1024 Paperclip.options[:command_path] = ["/usr/local/bin"] * 1024
Cocaine::CommandLine.path = "/something/else" Cocaine::CommandLine.path = "/something/else"
100.times do |x| 100.times do |x|
...@@ -42,24 +42,24 @@ class PaperclipTest < Test::Unit::TestCase ...@@ -42,24 +42,24 @@ class PaperclipTest < Test::Unit::TestCase
end end
context "Calling Paperclip.log without options[:logger] set" do context "Calling Paperclip.log without options[:logger] set" do
setup do before do
Paperclip.logger = nil Paperclip.logger = nil
Paperclip.options[:logger] = nil Paperclip.options[:logger] = nil
end end
teardown do after do
Paperclip.options[:logger] = ActiveRecord::Base.logger Paperclip.options[:logger] = ActiveRecord::Base.logger
Paperclip.logger = ActiveRecord::Base.logger Paperclip.logger = ActiveRecord::Base.logger
end end
should "not raise an error when log is called" do it "not raise an error when log is called" do
silence_stream(STDOUT) do silence_stream(STDOUT) do
Paperclip.log('something') Paperclip.log('something')
end end
end end
end end
context "Calling Paperclip.run with a logger" do context "Calling Paperclip.run with a logger" do
should "pass the defined logger if :log_command is set" do it "pass the defined logger if :log_command is set" do
Paperclip.options[:log_command] = true Paperclip.options[:log_command] = true
Cocaine::CommandLine.expects(:new).with("convert", "stuff", :logger => Paperclip.logger).returns(stub(:run)) Cocaine::CommandLine.expects(:new).with("convert", "stuff", :logger => Paperclip.logger).returns(stub(:run))
Paperclip.run("convert", "stuff") Paperclip.run("convert", "stuff")
...@@ -67,7 +67,7 @@ class PaperclipTest < Test::Unit::TestCase ...@@ -67,7 +67,7 @@ class PaperclipTest < Test::Unit::TestCase
end end
context "Paperclip.each_instance_with_attachment" do context "Paperclip.each_instance_with_attachment" do
setup do before do
@file = File.new(fixture_file("5k.png"), 'rb') @file = File.new(fixture_file("5k.png"), 'rb')
d1 = Dummy.create(:avatar => @file) d1 = Dummy.create(:avatar => @file)
d2 = Dummy.create d2 = Dummy.create
...@@ -75,47 +75,47 @@ class PaperclipTest < Test::Unit::TestCase ...@@ -75,47 +75,47 @@ class PaperclipTest < Test::Unit::TestCase
@expected = [d1, d3] @expected = [d1, d3]
end end
teardown { @file.close } after { @file.close }
should "yield every instance of a model that has an attachment" do it "yield every instance of a model that has an attachment" do
actual = [] actual = []
Paperclip.each_instance_with_attachment("Dummy", "avatar") do |instance| Paperclip.each_instance_with_attachment("Dummy", "avatar") do |instance|
actual << instance actual << instance
end end
assert_same_elements @expected, actual expect(actual).to match_array @expected
end end
end end
should "raise when sent #processor and the name of a class that doesn't exist" do it "raise when sent #processor and the name of a class that doesn't exist" do
assert_raises(NameError){ Paperclip.processor(:boogey_man) } assert_raises(LoadError){ Paperclip.processor(:boogey_man) }
end end
should "return a class when sent #processor and the name of a class under Paperclip" do it "return a class when sent #processor and the name of a class under Paperclip" do
assert_equal ::Paperclip::Thumbnail, Paperclip.processor(:thumbnail) assert_equal ::Paperclip::Thumbnail, Paperclip.processor(:thumbnail)
end end
should "get a class from a namespaced class name" do it "get a class from a namespaced class name" do
class ::One; class Two; end; end class ::One; class Two; end; end
assert_equal ::One::Two, Paperclip.class_for("One::Two") assert_equal ::One::Two, Paperclip.class_for("One::Two")
end end
should "raise when class doesn't exist in specified namespace" do it "raise when class doesn't exist in specified namespace" do
class ::Three; end class ::Three; end
class ::Four; end class ::Four; end
assert_raise NameError do assert_raises NameError do
Paperclip.class_for("Three::Four") Paperclip.class_for("Three::Four")
end end
end end
context "An ActiveRecord model with an 'avatar' attachment" do context "An ActiveRecord model with an 'avatar' attachment" do
setup do before do
rebuild_model :path => "tmp/:class/omg/:style.:extension" rebuild_model :path => "tmp/:class/omg/:style.:extension"
@file = File.new(fixture_file("5k.png"), 'rb') @file = File.new(fixture_file("5k.png"), 'rb')
end end
teardown { @file.close } after { @file.close }
should "not error when trying to also create a 'blah' attachment" do it "not error when trying to also create a 'blah' attachment" do
assert_nothing_raised do assert_nothing_raised do
Dummy.class_eval do Dummy.class_eval do
has_attached_file :blah has_attached_file :blah
...@@ -125,14 +125,14 @@ class PaperclipTest < Test::Unit::TestCase ...@@ -125,14 +125,14 @@ class PaperclipTest < Test::Unit::TestCase
if using_protected_attributes? if using_protected_attributes?
context "that is attr_protected" do context "that is attr_protected" do
setup do before do
Dummy.class_eval do Dummy.class_eval do
attr_protected :avatar attr_protected :avatar
end end
@dummy = Dummy.new @dummy = Dummy.new
end end
should "not assign the avatar on mass-set" do it "not assign the avatar on mass-set" do
@dummy.attributes = { :other => "I'm set!", @dummy.attributes = { :other => "I'm set!",
:avatar => @file } :avatar => @file }
...@@ -140,7 +140,7 @@ class PaperclipTest < Test::Unit::TestCase ...@@ -140,7 +140,7 @@ class PaperclipTest < Test::Unit::TestCase
assert ! @dummy.avatar? assert ! @dummy.avatar?
end end
should "still allow assigment on normal set" do it "still allow assigment on normal set" do
@dummy.other = "I'm set!" @dummy.other = "I'm set!"
@dummy.avatar = @file @dummy.avatar = @file
...@@ -151,42 +151,42 @@ class PaperclipTest < Test::Unit::TestCase ...@@ -151,42 +151,42 @@ class PaperclipTest < Test::Unit::TestCase
end end
context "with a subclass" do context "with a subclass" do
setup do before do
class ::SubDummy < Dummy; end class ::SubDummy < Dummy; end
end end
should "be able to use the attachment from the subclass" do it "be able to use the attachment from the subclass" do
assert_nothing_raised do assert_nothing_raised do
@subdummy = SubDummy.create(:avatar => @file) @subdummy = SubDummy.create(:avatar => @file)
end end
end end
teardown do after do
SubDummy.delete_all SubDummy.delete_all
Object.send(:remove_const, "SubDummy") rescue nil Object.send(:remove_const, "SubDummy") rescue nil
end end
end end
should "have an #avatar method" do it "have an avatar getter method" do
assert Dummy.new.respond_to?(:avatar) assert Dummy.new.respond_to?(:avatar)
end end
should "have an #avatar= method" do it "have an avatar setter method" do
assert Dummy.new.respond_to?(:avatar=) assert Dummy.new.respond_to?(:avatar=)
end end
context "that is valid" do context "that is valid" do
setup do before do
@dummy = Dummy.new @dummy = Dummy.new
@dummy.avatar = @file @dummy.avatar = @file
end end
should "be valid" do it "be valid" do
assert @dummy.valid? assert @dummy.valid?
end end
end end
should "not have Attachment in the ActiveRecord::Base namespace" do it "not have Attachment in the ActiveRecord::Base namespace" do
assert_raises(NameError) do assert_raises(NameError) do
ActiveRecord::Base::Attachment ActiveRecord::Base::Attachment
end end
...@@ -194,7 +194,7 @@ class PaperclipTest < Test::Unit::TestCase ...@@ -194,7 +194,7 @@ class PaperclipTest < Test::Unit::TestCase
end end
context "configuring a custom processor" do context "configuring a custom processor" do
setup do before do
@freedom_processor = Class.new do @freedom_processor = Class.new do
def make(file, options = {}, attachment = nil) def make(file, options = {}, attachment = nil)
file file
...@@ -206,11 +206,11 @@ class PaperclipTest < Test::Unit::TestCase ...@@ -206,11 +206,11 @@ class PaperclipTest < Test::Unit::TestCase
end end
end end
should "be able to find the custom processor" do it "be able to find the custom processor" do
assert_equal @freedom_processor, Paperclip.processor(:freedom) assert_equal @freedom_processor, Paperclip.processor(:freedom)
end end
teardown do after do
Paperclip.clear_processors! Paperclip.clear_processors!
end end
end end
......
require './test/helper' require 'spec_helper'
class PluralCacheTest < Test::Unit::TestCase describe 'Plural cache' do
should 'cache pluralizations' do it 'cache pluralizations' do
cache = Paperclip::Interpolations::PluralCache.new cache = Paperclip::Interpolations::PluralCache.new
word = "box" word = "box"
...@@ -11,7 +11,7 @@ class PluralCacheTest < Test::Unit::TestCase ...@@ -11,7 +11,7 @@ class PluralCacheTest < Test::Unit::TestCase
cache.pluralize(word) cache.pluralize(word)
end end
should 'cache pluralizations and underscores' do it 'cache pluralizations and underscores' do
cache = Paperclip::Interpolations::PluralCache.new cache = Paperclip::Interpolations::PluralCache.new
word = "BigBox" word = "BigBox"
...@@ -22,13 +22,13 @@ class PluralCacheTest < Test::Unit::TestCase ...@@ -22,13 +22,13 @@ class PluralCacheTest < Test::Unit::TestCase
cache.underscore_and_pluralize(word) cache.underscore_and_pluralize(word)
end end
should 'pluralize words' do it 'pluralize words' do
cache = Paperclip::Interpolations::PluralCache.new cache = Paperclip::Interpolations::PluralCache.new
word = "box" word = "box"
assert_equal "boxes", cache.pluralize(word) assert_equal "boxes", cache.pluralize(word)
end end
should 'pluralize and underscore words' do it 'pluralize and underscore words' do
cache = Paperclip::Interpolations::PluralCache.new cache = Paperclip::Interpolations::PluralCache.new
word = "BigBox" word = "BigBox"
assert_equal "big_boxes", cache.underscore_and_pluralize(word) assert_equal "big_boxes", cache.underscore_and_pluralize(word)
......
require './test/helper' require 'spec_helper'
class ProcessorTest < Test::Unit::TestCase describe Paperclip::Processor do
should "instantiate and call #make when sent #make to the class" do it "instantiate and call #make when sent #make to the class" do
processor = mock processor = mock
processor.expects(:make).with() processor.expects(:make).with()
Paperclip::Processor.expects(:new).with(:one, :two, :three).returns(processor) Paperclip::Processor.expects(:new).with(:one, :two, :three).returns(processor)
...@@ -9,7 +9,7 @@ class ProcessorTest < Test::Unit::TestCase ...@@ -9,7 +9,7 @@ class ProcessorTest < Test::Unit::TestCase
end end
context "Calling #convert" do context "Calling #convert" do
should "run the convert command with Cocaine" do it "run the convert command with Cocaine" do
Paperclip.options[:log_command] = false Paperclip.options[:log_command] = false
Cocaine::CommandLine.expects(:new).with("convert", "stuff", {}).returns(stub(:run)) Cocaine::CommandLine.expects(:new).with("convert", "stuff", {}).returns(stub(:run))
Paperclip::Processor.new('filename').convert("stuff") Paperclip::Processor.new('filename').convert("stuff")
...@@ -17,7 +17,7 @@ class ProcessorTest < Test::Unit::TestCase ...@@ -17,7 +17,7 @@ class ProcessorTest < Test::Unit::TestCase
end end
context "Calling #identify" do context "Calling #identify" do
should "run the identify command with Cocaine" do it "run the identify command with Cocaine" do
Paperclip.options[:log_command] = false Paperclip.options[:log_command] = false
Cocaine::CommandLine.expects(:new).with("identify", "stuff", {}).returns(stub(:run)) Cocaine::CommandLine.expects(:new).with("identify", "stuff", {}).returns(stub(:run))
Paperclip::Processor.new('filename').identify("stuff") Paperclip::Processor.new('filename').identify("stuff")
......
require './test/helper' require 'spec_helper'
require 'rake' require 'rake'
load './lib/tasks/paperclip.rake' load './lib/tasks/paperclip.rake'
class RakeTest < Test::Unit::TestCase describe Rake do
context "calling `rake paperclip:refresh:thumbnails`" do context "calling `rake paperclip:refresh:thumbnails`" do
setup do before do
rebuild_model rebuild_model
Paperclip::Task.stubs(:obtain_class).returns('Dummy') Paperclip::Task.stubs(:obtain_class).returns('Dummy')
@bogus_instance = Dummy.new @bogus_instance = Dummy.new
...@@ -16,22 +16,22 @@ class RakeTest < Test::Unit::TestCase ...@@ -16,22 +16,22 @@ class RakeTest < Test::Unit::TestCase
Paperclip.stubs(:each_instance_with_attachment).multiple_yields @bogus_instance, @valid_instance Paperclip.stubs(:each_instance_with_attachment).multiple_yields @bogus_instance, @valid_instance
end end
context "when there is an exception in reprocess!" do context "when there is an exception in reprocess!" do
setup do before do
@bogus_instance.avatar.stubs(:reprocess!).raises @bogus_instance.avatar.stubs(:reprocess!).raises
end end
should "catch the exception" do it "catch the exception" do
assert_nothing_raised do assert_nothing_raised do
::Rake::Task['paperclip:refresh:thumbnails'].execute ::Rake::Task['paperclip:refresh:thumbnails'].execute
end end
end end
should "continue to the next instance" do it "continue to the next instance" do
@valid_instance.avatar.expects(:reprocess!) @valid_instance.avatar.expects(:reprocess!)
::Rake::Task['paperclip:refresh:thumbnails'].execute ::Rake::Task['paperclip:refresh:thumbnails'].execute
end end
should "print the exception" do it "print the exception" do
exception_msg = 'Some Exception' exception_msg = 'Some Exception'
@bogus_instance.avatar.stubs(:reprocess!).raises(exception_msg) @bogus_instance.avatar.stubs(:reprocess!).raises(exception_msg)
Paperclip::Task.expects(:log_error).with do |str| Paperclip::Task.expects(:log_error).with do |str|
...@@ -40,14 +40,14 @@ class RakeTest < Test::Unit::TestCase ...@@ -40,14 +40,14 @@ class RakeTest < Test::Unit::TestCase
::Rake::Task['paperclip:refresh:thumbnails'].execute ::Rake::Task['paperclip:refresh:thumbnails'].execute
end end
should "print the class name" do it "print the class name" do
Paperclip::Task.expects(:log_error).with do |str| Paperclip::Task.expects(:log_error).with do |str|
str.match 'Dummy' str.match 'Dummy'
end end
::Rake::Task['paperclip:refresh:thumbnails'].execute ::Rake::Task['paperclip:refresh:thumbnails'].execute
end end
should "print the instance ID" do it "print the instance ID" do
Paperclip::Task.expects(:log_error).with do |str| Paperclip::Task.expects(:log_error).with do |str|
str.match "ID #{@bogus_instance.id}" str.match "ID #{@bogus_instance.id}"
end end
...@@ -56,19 +56,19 @@ class RakeTest < Test::Unit::TestCase ...@@ -56,19 +56,19 @@ class RakeTest < Test::Unit::TestCase
end end
context "when there is an error in reprocess!" do context "when there is an error in reprocess!" do
setup do before do
@errors = mock('errors') @errors = mock('errors')
@errors.stubs(:full_messages).returns(['']) @errors.stubs(:full_messages).returns([''])
@errors.stubs(:blank?).returns(false) @errors.stubs(:blank?).returns(false)
@bogus_instance.stubs(:errors).returns(@errors) @bogus_instance.stubs(:errors).returns(@errors)
end end
should "continue to the next instance" do it "continue to the next instance" do
@valid_instance.avatar.expects(:reprocess!) @valid_instance.avatar.expects(:reprocess!)
::Rake::Task['paperclip:refresh:thumbnails'].execute ::Rake::Task['paperclip:refresh:thumbnails'].execute
end end
should "print the error" do it "print the error" do
error_msg = 'Some Error' error_msg = 'Some Error'
@errors.stubs(:full_messages).returns([error_msg]) @errors.stubs(:full_messages).returns([error_msg])
Paperclip::Task.expects(:log_error).with do |str| Paperclip::Task.expects(:log_error).with do |str|
...@@ -77,14 +77,14 @@ class RakeTest < Test::Unit::TestCase ...@@ -77,14 +77,14 @@ class RakeTest < Test::Unit::TestCase
::Rake::Task['paperclip:refresh:thumbnails'].execute ::Rake::Task['paperclip:refresh:thumbnails'].execute
end end
should "print the class name" do it "print the class name" do
Paperclip::Task.expects(:log_error).with do |str| Paperclip::Task.expects(:log_error).with do |str|
str.match 'Dummy' str.match 'Dummy'
end end
::Rake::Task['paperclip:refresh:thumbnails'].execute ::Rake::Task['paperclip:refresh:thumbnails'].execute
end end
should "print the instance ID" do it "print the instance ID" do
Paperclip::Task.expects(:log_error).with do |str| Paperclip::Task.expects(:log_error).with do |str|
str.match "ID #{@bogus_instance.id}" str.match "ID #{@bogus_instance.id}"
end end
...@@ -94,7 +94,7 @@ class RakeTest < Test::Unit::TestCase ...@@ -94,7 +94,7 @@ class RakeTest < Test::Unit::TestCase
end end
context "Paperclip::Task.log_error method" do context "Paperclip::Task.log_error method" do
should "print its argument to STDERR" do it "print its argument to STDERR" do
msg = 'Some Message' msg = 'Some Message'
$stderr.expects(:puts).with(msg) $stderr.expects(:puts).with(msg)
Paperclip::Task.log_error(msg) Paperclip::Task.log_error(msg)
......
require './test/helper' require 'spec_helper'
class FileSystemTest < Test::Unit::TestCase describe Paperclip::Storage::Filesystem do
context "Filesystem" do context "Filesystem" do
context "normal file" do context "normal file" do
setup do before do
rebuild_model :styles => { :thumbnail => "25x25#" } rebuild_model :styles => { :thumbnail => "25x25#" }
@dummy = Dummy.create! @dummy = Dummy.create!
...@@ -11,23 +11,23 @@ class FileSystemTest < Test::Unit::TestCase ...@@ -11,23 +11,23 @@ class FileSystemTest < Test::Unit::TestCase
@dummy.avatar = @file @dummy.avatar = @file
end end
teardown { @file.close } after { @file.close }
should "allow file assignment" do it "allow file assignment" do
assert @dummy.save assert @dummy.save
end end
should "store the original" do it "store the original" do
@dummy.save @dummy.save
assert_file_exists(@dummy.avatar.path) assert_file_exists(@dummy.avatar.path)
end end
should "store the thumbnail" do it "store the thumbnail" do
@dummy.save @dummy.save
assert_file_exists(@dummy.avatar.path(:thumbnail)) assert_file_exists(@dummy.avatar.path(:thumbnail))
end end
should "be rewinded after flush_writes" do it "be rewinded after flush_writes" do
@dummy.avatar.instance_eval "def after_flush_writes; end" @dummy.avatar.instance_eval "def after_flush_writes; end"
files = @dummy.avatar.queued_for_write.values files = @dummy.avatar.queued_for_write.values
...@@ -35,14 +35,14 @@ class FileSystemTest < Test::Unit::TestCase ...@@ -35,14 +35,14 @@ class FileSystemTest < Test::Unit::TestCase
assert files.none?(&:eof?), "Expect all the files to be rewinded." assert files.none?(&:eof?), "Expect all the files to be rewinded."
end end
should "be removed after after_flush_writes" do it "be removed after after_flush_writes" do
paths = @dummy.avatar.queued_for_write.values.map(&:path) paths = @dummy.avatar.queued_for_write.values.map(&:path)
@dummy.save @dummy.save
assert paths.none?{ |path| File.exists?(path) }, assert paths.none?{ |path| File.exists?(path) },
"Expect all the files to be deleted." "Expect all the files to be deleted."
end end
should 'copy the file to a known location with copy_to_local_file' do it 'copy the file to a known location with copy_to_local_file' do
tempfile = Tempfile.new("known_location") tempfile = Tempfile.new("known_location")
@dummy.avatar.copy_to_local_file(:original, tempfile.path) @dummy.avatar.copy_to_local_file(:original, tempfile.path)
tempfile.rewind tempfile.rewind
...@@ -52,7 +52,7 @@ class FileSystemTest < Test::Unit::TestCase ...@@ -52,7 +52,7 @@ class FileSystemTest < Test::Unit::TestCase
end end
context "with file that has space in file name" do context "with file that has space in file name" do
setup do before do
rebuild_model :styles => { :thumbnail => "25x25#" } rebuild_model :styles => { :thumbnail => "25x25#" }
@dummy = Dummy.create! @dummy = Dummy.create!
...@@ -61,17 +61,17 @@ class FileSystemTest < Test::Unit::TestCase ...@@ -61,17 +61,17 @@ class FileSystemTest < Test::Unit::TestCase
@dummy.save @dummy.save
end end
teardown { @file.close } after { @file.close }
should "store the file" do it "store the file" do
assert_file_exists(@dummy.avatar.path) assert_file_exists(@dummy.avatar.path)
end end
should "return a replaced version for path" do it "return a replaced version for path" do
assert_match /.+\/spaced_file\.png/, @dummy.avatar.path assert_match /.+\/spaced_file\.png/, @dummy.avatar.path
end end
should "return a replaced version for url" do it "return a replaced version for url" do
assert_match /.+\/spaced_file\.png/, @dummy.avatar.url assert_match /.+\/spaced_file\.png/, @dummy.avatar.url
end end
end end
......
require './test/helper' require 'spec_helper'
require 'aws'
unless ENV["S3_BUCKET"].blank? unless ENV["S3_BUCKET"].blank?
class S3LiveTest < Test::Unit::TestCase describe Paperclip::Storage::S3, 'Live S3' do
context "when assigning an S3 attachment directly to another model" do context "when assigning an S3 attachment directly to another model" do
setup do before do
@s3_credentials = File.new(fixture_file("s3.yml"))
rebuild_model :styles => { :thumb => "100x100", :square => "32x32#" }, rebuild_model :styles => { :thumb => "100x100", :square => "32x32#" },
:storage => :s3, :storage => :s3,
:bucket => ENV["S3_BUCKET"], :bucket => ENV["S3_BUCKET"],
:path => ":class/:attachment/:id/:style.:extension", :path => ":class/:attachment/:id/:style.:extension",
:s3_credentials => @s3_credentials :s3_credentials => {
:aws_access_key_id => ENV['AWS_ACCESS_KEY_ID'],
:aws_secre_access_key => ENV['AWS_SECRET_ACCESS_KEY']
}
@file = File.new(fixture_file("5k.png")) @file = File.new(fixture_file("5k.png"))
end end
should "not raise any error" do it "not raise any error" do
@attachment = Dummy.new.avatar @attachment = Dummy.new.avatar
@attachment.assign(@file) @attachment.assign(@file)
@attachment.save @attachment.save
...@@ -25,7 +26,7 @@ unless ENV["S3_BUCKET"].blank? ...@@ -25,7 +26,7 @@ unless ENV["S3_BUCKET"].blank?
@attachment2.save @attachment2.save
end end
should "allow assignment from another S3 object" do it "allow assignment from another S3 object" do
@attachment = Dummy.new.avatar @attachment = Dummy.new.avatar
@attachment.assign(@file) @attachment.assign(@file)
@attachment.save @attachment.save
...@@ -35,62 +36,64 @@ unless ENV["S3_BUCKET"].blank? ...@@ -35,62 +36,64 @@ unless ENV["S3_BUCKET"].blank?
@attachment2.save @attachment2.save
end end
teardown { [@s3_credentials, @file].each(&:close) } after { @file.close }
end end
context "Generating an expiring url on a nonexistant attachment" do context "Generating an expiring url on a nonexistant attachment" do
setup do before do
@s3_credentials = File.new(fixture_file("s3.yml"))
rebuild_model :styles => { :thumb => "100x100", :square => "32x32#" }, rebuild_model :styles => { :thumb => "100x100", :square => "32x32#" },
:storage => :s3, :storage => :s3,
:bucket => ENV["S3_BUCKET"], :bucket => ENV["S3_BUCKET"],
:path => ":class/:attachment/:id/:style.:extension", :path => ":class/:attachment/:id/:style.:extension",
:s3_credentials => @s3_credentials :s3_credentials => {
:aws_access_key_id => ENV['AWS_ACCESS_KEY_ID'],
:aws_secre_access_key => ENV['AWS_SECRET_ACCESS_KEY']
}
@dummy = Dummy.new @dummy = Dummy.new
end end
should "return nil" do it "returns a missing url" do
assert_nil @dummy.avatar.expiring_url expect(@dummy.avatar.expiring_url).to eq @dummy.avatar.url
end end
end end
context "Using S3 for real, an attachment with S3 storage" do context "Using S3 for real, an attachment with S3 storage" do
setup do before do
@s3_credentials = File.new(fixture_file("s3.yml"))
rebuild_model :styles => { :thumb => "100x100", :square => "32x32#" }, rebuild_model :styles => { :thumb => "100x100", :square => "32x32#" },
:storage => :s3, :storage => :s3,
:bucket => ENV["S3_BUCKET"], :bucket => ENV["S3_BUCKET"],
:path => ":class/:attachment/:id/:style.:extension", :path => ":class/:attachment/:id/:style.:extension",
:s3_credentials => @s3_credentials :s3_credentials => {
:aws_access_key_id => ENV['AWS_ACCESS_KEY_ID'],
:aws_secre_access_key => ENV['AWS_SECRET_ACCESS_KEY']
}
Dummy.delete_all Dummy.delete_all
@dummy = Dummy.new @dummy = Dummy.new
end end
teardown { @s3_credentials.close } it "be extended by the S3 module" do
should "be extended by the S3 module" do
assert Dummy.new.avatar.is_a?(Paperclip::Storage::S3) assert Dummy.new.avatar.is_a?(Paperclip::Storage::S3)
end end
context "when assigned" do context "when assigned" do
setup do before do
@file = File.new(fixture_file('5k.png'), 'rb') @file = File.new(fixture_file('5k.png'), 'rb')
@dummy.avatar = @file @dummy.avatar = @file
end end
teardown do after do
@file.close @file.close
@dummy.destroy @dummy.destroy
end end
context "and saved" do context "and saved" do
setup do before do
@dummy.save @dummy.save
end end
should "be on S3" do it "be on S3" do
assert true assert true
end end
end end
...@@ -98,12 +101,14 @@ unless ENV["S3_BUCKET"].blank? ...@@ -98,12 +101,14 @@ unless ENV["S3_BUCKET"].blank?
end end
context "An attachment that uses S3 for storage and has spaces in file name" do context "An attachment that uses S3 for storage and has spaces in file name" do
setup do before do
@s3_credentials = File.new(fixture_file("s3.yml"))
rebuild_model :styles => { :thumb => "100x100", :square => "32x32#" }, rebuild_model :styles => { :thumb => "100x100", :square => "32x32#" },
:storage => :s3, :storage => :s3,
:bucket => ENV["S3_BUCKET"], :bucket => ENV["S3_BUCKET"],
:s3_credentials => @s3_credentials :s3_credentials => {
:aws_access_key_id => ENV['AWS_ACCESS_KEY_ID'],
:aws_secre_access_key => ENV['AWS_SECRET_ACCESS_KEY']
}
Dummy.delete_all Dummy.delete_all
@file = File.new(fixture_file('spaced file.png'), 'rb') @file = File.new(fixture_file('spaced file.png'), 'rb')
...@@ -112,25 +117,23 @@ unless ENV["S3_BUCKET"].blank? ...@@ -112,25 +117,23 @@ unless ENV["S3_BUCKET"].blank?
@dummy.save @dummy.save
end end
teardown { @s3_credentials.close } it "return a replaced version for path" do
should "return a replaced version for path" do
assert_match /.+\/spaced_file\.png/, @dummy.avatar.path assert_match /.+\/spaced_file\.png/, @dummy.avatar.path
end end
should "return a replaced version for url" do it "return a replaced version for url" do
assert_match /.+\/spaced_file\.png/, @dummy.avatar.url assert_match /.+\/spaced_file\.png/, @dummy.avatar.url
end end
should "be accessible" do it "be accessible" do
assert_success_response @dummy.avatar.url assert_success_response @dummy.avatar.url
end end
should "be reprocessable" do it "be reprocessable" do
assert @dummy.avatar.reprocess! assert @dummy.avatar.reprocess!
end end
should "be destroyable" do it "be destroyable" do
url = @dummy.avatar.url url = @dummy.avatar.url
@dummy.destroy @dummy.destroy
assert_not_found_response url assert_not_found_response url
...@@ -138,38 +141,38 @@ unless ENV["S3_BUCKET"].blank? ...@@ -138,38 +141,38 @@ unless ENV["S3_BUCKET"].blank?
end end
context "An attachment that uses S3 for storage and uses AES256 encryption" do context "An attachment that uses S3 for storage and uses AES256 encryption" do
setup do before do
@s3_credentials = File.new(fixture_file("s3.yml"))
rebuild_model :styles => { :thumb => "100x100", :square => "32x32#" }, rebuild_model :styles => { :thumb => "100x100", :square => "32x32#" },
:storage => :s3, :storage => :s3,
:bucket => ENV["S3_BUCKET"], :bucket => ENV["S3_BUCKET"],
:path => ":class/:attachment/:id/:style.:extension", :path => ":class/:attachment/:id/:style.:extension",
:s3_credentials => @s3_credentials, :s3_credentials => {
:aws_access_key_id => ENV['AWS_ACCESS_KEY_ID'],
:aws_secre_access_key => ENV['AWS_SECRET_ACCESS_KEY']
},
:s3_server_side_encryption => :aes256 :s3_server_side_encryption => :aes256
Dummy.delete_all Dummy.delete_all
@dummy = Dummy.new @dummy = Dummy.new
end end
teardown { @s3_credentials.close }
context "when assigned" do context "when assigned" do
setup do before do
@file = File.new(fixture_file('5k.png'), 'rb') @file = File.new(fixture_file('5k.png'), 'rb')
@dummy.avatar = @file @dummy.avatar = @file
end end
teardown do after do
@file.close @file.close
@dummy.destroy @dummy.destroy
end end
context "and saved" do context "and saved" do
setup do before do
@dummy.save @dummy.save
end end
should "be encrypted on S3" do it "be encrypted on S3" do
assert @dummy.avatar.s3_object.server_side_encryption == :aes256 assert @dummy.avatar.s3_object.server_side_encryption == :aes256
end end
end end
......
# encoding: utf-8 # encoding: utf-8
require './test/helper' require 'spec_helper'
class StyleTest < Test::Unit::TestCase
describe Paperclip::Style do
context "A style rule" do context "A style rule" do
setup do before do
@attachment = attachment :path => ":basename.:extension", @attachment = attachment :path => ":basename.:extension",
:styles => { :foo => {:geometry => "100x100#", :format => :png} }, :styles => { :foo => {:geometry => "100x100#", :format => :png} },
:whiny => true :whiny => true
@style = @attachment.styles[:foo] @style = @attachment.styles[:foo]
end end
should "be held as a Style object" do it "be held as a Style object" do
assert_kind_of Paperclip::Style, @style expect(@style).to be_a Paperclip::Style
end end
should "get processors from the attachment definition" do it "get processors from the attachment definition" do
assert_equal [:thumbnail], @style.processors assert_equal [:thumbnail], @style.processors
end end
should "have the right geometry" do it "have the right geometry" do
assert_equal "100x100#", @style.geometry assert_equal "100x100#", @style.geometry
end end
should "be whiny if the attachment is" do it "be whiny if the attachment is" do
assert @style.whiny? assert @style.whiny?
end end
should "respond to hash notation" do it "respond to hash notation" do
assert_equal [:thumbnail], @style[:processors] assert_equal [:thumbnail], @style[:processors]
assert_equal "100x100#", @style[:geometry] assert_equal "100x100#", @style[:geometry]
end end
...@@ -38,7 +37,7 @@ class StyleTest < Test::Unit::TestCase ...@@ -38,7 +37,7 @@ class StyleTest < Test::Unit::TestCase
end end
context "A style rule with properties supplied as procs" do context "A style rule with properties supplied as procs" do
setup do before do
@attachment = attachment :path => ":basename.:extension", @attachment = attachment :path => ":basename.:extension",
:whiny_thumbnails => true, :whiny_thumbnails => true,
:processors => lambda {|a| [:test]}, :processors => lambda {|a| [:test]},
...@@ -52,7 +51,7 @@ class StyleTest < Test::Unit::TestCase ...@@ -52,7 +51,7 @@ class StyleTest < Test::Unit::TestCase
} }
end end
should "call procs when they are needed" do it "call procs when they are needed" do
assert_equal "300x300#", @attachment.styles[:foo].geometry assert_equal "300x300#", @attachment.styles[:foo].geometry
assert_equal "300x300#", @attachment.styles[:bar].geometry assert_equal "300x300#", @attachment.styles[:bar].geometry
assert_equal [:test], @attachment.styles[:foo].processors assert_equal [:test], @attachment.styles[:foo].processors
...@@ -63,7 +62,7 @@ class StyleTest < Test::Unit::TestCase ...@@ -63,7 +62,7 @@ class StyleTest < Test::Unit::TestCase
end end
context "An attachment with style rules in various forms" do context "An attachment with style rules in various forms" do
setup do before do
styles = {} styles = {}
styles[:aslist] = ["100x100", :png] styles[:aslist] = ["100x100", :png]
styles[:ashash] = {:geometry => "100x100", :format => :png} styles[:ashash] = {:geometry => "100x100", :format => :png}
...@@ -72,36 +71,36 @@ class StyleTest < Test::Unit::TestCase ...@@ -72,36 +71,36 @@ class StyleTest < Test::Unit::TestCase
:styles => styles :styles => styles
end end
should "have the right number of styles" do it "have the right number of styles" do
assert_kind_of Hash, @attachment.styles expect(@attachment.styles).to be_a Hash
assert_equal 3, @attachment.styles.size assert_equal 3, @attachment.styles.size
end end
should "have styles as Style objects" do it "have styles as Style objects" do
[:aslist, :ashash, :aslist].each do |s| [:aslist, :ashash, :aslist].each do |s|
assert_kind_of Paperclip::Style, @attachment.styles[s] expect(@attachment.styles[s]).to be_a Paperclip::Style
end end
end end
should "have the right geometries" do it "have the right geometries" do
[:aslist, :ashash, :aslist].each do |s| [:aslist, :ashash, :aslist].each do |s|
assert_equal @attachment.styles[s].geometry, "100x100" assert_equal @attachment.styles[s].geometry, "100x100"
end end
end end
should "have the right formats" do it "have the right formats" do
assert_equal @attachment.styles[:aslist].format, :png assert_equal @attachment.styles[:aslist].format, :png
assert_equal @attachment.styles[:ashash].format, :png assert_equal @attachment.styles[:ashash].format, :png
assert_nil @attachment.styles[:asstring].format assert_nil @attachment.styles[:asstring].format
end end
should "retain order" do it "retain order" do
assert_equal [:aslist, :ashash, :asstring], @attachment.styles.keys assert_equal [:aslist, :ashash, :asstring], @attachment.styles.keys
end end
end end
context "An attachment with :convert_options" do context "An attachment with :convert_options" do
should "not have called extra_options_for(:thumb/:large) on initialization" do it "not have called extra_options_for(:thumb/:large) on initialization" do
@attachment = attachment :path => ":basename.:extension", @attachment = attachment :path => ":basename.:extension",
:styles => {:thumb => "100x100", :large => "400x400"}, :styles => {:thumb => "100x100", :large => "400x400"},
:convert_options => {:all => "-do_stuff", :thumb => "-thumbnailize"} :convert_options => {:all => "-do_stuff", :thumb => "-thumbnailize"}
...@@ -109,7 +108,7 @@ class StyleTest < Test::Unit::TestCase ...@@ -109,7 +108,7 @@ class StyleTest < Test::Unit::TestCase
@style = @attachment.styles[:thumb] @style = @attachment.styles[:thumb]
end end
should "call extra_options_for(:thumb/:large) when convert options are requested" do it "call extra_options_for(:thumb/:large) when convert options are requested" do
@attachment = attachment :path => ":basename.:extension", @attachment = attachment :path => ":basename.:extension",
:styles => {:thumb => "100x100", :large => "400x400"}, :styles => {:thumb => "100x100", :large => "400x400"},
:convert_options => {:all => "-do_stuff", :thumb => "-thumbnailize"} :convert_options => {:all => "-do_stuff", :thumb => "-thumbnailize"}
...@@ -123,7 +122,7 @@ class StyleTest < Test::Unit::TestCase ...@@ -123,7 +122,7 @@ class StyleTest < Test::Unit::TestCase
end end
context "An attachment with :source_file_options" do context "An attachment with :source_file_options" do
should "not have called extra_source_file_options_for(:thumb/:large) on initialization" do it "not have called extra_source_file_options_for(:thumb/:large) on initialization" do
@attachment = attachment :path => ":basename.:extension", @attachment = attachment :path => ":basename.:extension",
:styles => {:thumb => "100x100", :large => "400x400"}, :styles => {:thumb => "100x100", :large => "400x400"},
:source_file_options => {:all => "-density 400", :thumb => "-depth 8"} :source_file_options => {:all => "-density 400", :thumb => "-depth 8"}
...@@ -131,7 +130,7 @@ class StyleTest < Test::Unit::TestCase ...@@ -131,7 +130,7 @@ class StyleTest < Test::Unit::TestCase
@style = @attachment.styles[:thumb] @style = @attachment.styles[:thumb]
end end
should "call extra_options_for(:thumb/:large) when convert options are requested" do it "call extra_options_for(:thumb/:large) when convert options are requested" do
@attachment = attachment :path => ":basename.:extension", @attachment = attachment :path => ":basename.:extension",
:styles => {:thumb => "100x100", :large => "400x400"}, :styles => {:thumb => "100x100", :large => "400x400"},
:source_file_options => {:all => "-density 400", :thumb => "-depth 8"} :source_file_options => {:all => "-density 400", :thumb => "-depth 8"}
...@@ -145,7 +144,7 @@ class StyleTest < Test::Unit::TestCase ...@@ -145,7 +144,7 @@ class StyleTest < Test::Unit::TestCase
end end
context "A style rule with its own :processors" do context "A style rule with its own :processors" do
setup do before do
@attachment = attachment :path => ":basename.:extension", @attachment = attachment :path => ":basename.:extension",
:styles => { :styles => {
:foo => { :foo => {
...@@ -158,19 +157,19 @@ class StyleTest < Test::Unit::TestCase ...@@ -158,19 +157,19 @@ class StyleTest < Test::Unit::TestCase
@style = @attachment.styles[:foo] @style = @attachment.styles[:foo]
end end
should "not get processors from the attachment" do it "not get processors from the attachment" do
@attachment.expects(:processors).never @attachment.expects(:processors).never
assert_not_equal [:thumbnail], @style.processors assert_not_equal [:thumbnail], @style.processors
end end
should "report its own processors" do it "report its own processors" do
assert_equal [:test], @style.processors assert_equal [:test], @style.processors
end end
end end
context "A style rule with :processors supplied as procs" do context "A style rule with :processors supplied as procs" do
setup do before do
@attachment = attachment :path => ":basename.:extension", @attachment = attachment :path => ":basename.:extension",
:styles => { :styles => {
:foo => { :foo => {
...@@ -182,17 +181,17 @@ class StyleTest < Test::Unit::TestCase ...@@ -182,17 +181,17 @@ class StyleTest < Test::Unit::TestCase
:processors => [:thumbnail] :processors => [:thumbnail]
end end
should "defer processing of procs until they are needed" do it "defer processing of procs until they are needed" do
assert_kind_of Proc, @attachment.styles[:foo].instance_variable_get("@processors") expect(@attachment.styles[:foo].instance_variable_get("@processors")).to be_a Proc
end end
should "call procs when they are needed" do it "call procs when they are needed" do
assert_equal [:test], @attachment.styles[:foo].processors assert_equal [:test], @attachment.styles[:foo].processors
end end
end end
context "An attachment with :convert_options and :source_file_options in :styles" do context "An attachment with :convert_options and :source_file_options in :styles" do
setup do before do
@attachment = attachment :path => ":basename.:extension", @attachment = attachment :path => ":basename.:extension",
:styles => { :styles => {
:thumb => "100x100", :thumb => "100x100",
...@@ -205,19 +204,19 @@ class StyleTest < Test::Unit::TestCase ...@@ -205,19 +204,19 @@ class StyleTest < Test::Unit::TestCase
@file.stubs(:original_filename).returns("file.jpg") @file.stubs(:original_filename).returns("file.jpg")
end end
should "have empty options for :thumb style" do it "have empty options for :thumb style" do
assert_equal "", @attachment.styles[:thumb].processor_options[:convert_options] assert_equal "", @attachment.styles[:thumb].processor_options[:convert_options]
assert_equal "", @attachment.styles[:thumb].processor_options[:source_file_options] assert_equal "", @attachment.styles[:thumb].processor_options[:source_file_options]
end end
should "have the right options for :large style" do it "have the right options for :large style" do
assert_equal "-do_stuff", @attachment.styles[:large].processor_options[:convert_options] assert_equal "-do_stuff", @attachment.styles[:large].processor_options[:convert_options]
assert_equal "-do_extra_stuff", @attachment.styles[:large].processor_options[:source_file_options] assert_equal "-do_extra_stuff", @attachment.styles[:large].processor_options[:source_file_options]
end end
end end
context "A style rule supplied with default format" do context "A style rule supplied with default format" do
setup do before do
@attachment = attachment :default_format => :png, @attachment = attachment :default_format => :png,
:styles => { :styles => {
:asstring => "300x300#", :asstring => "300x300#",
...@@ -229,24 +228,24 @@ class StyleTest < Test::Unit::TestCase ...@@ -229,24 +228,24 @@ class StyleTest < Test::Unit::TestCase
} }
end end
should "have the right number of styles" do it "have the right number of styles" do
assert_kind_of Hash, @attachment.styles expect(@attachment.styles).to be_a Hash
assert_equal 3, @attachment.styles.size assert_equal 3, @attachment.styles.size
end end
should "have styles as Style objects" do it "have styles as Style objects" do
[:aslist, :ashash, :aslist].each do |s| [:aslist, :ashash, :aslist].each do |s|
assert_kind_of Paperclip::Style, @attachment.styles[s] expect(@attachment.styles[s]).to be_a Paperclip::Style
end end
end end
should "have the right geometries" do it "have the right geometries" do
[:aslist, :ashash, :aslist].each do |s| [:aslist, :ashash, :aslist].each do |s|
assert_equal @attachment.styles[s].geometry, "300x300#" assert_equal @attachment.styles[s].geometry, "300x300#"
end end
end end
should "have the right formats" do it "have the right formats" do
assert_equal @attachment.styles[:aslist].format, :jpg assert_equal @attachment.styles[:aslist].format, :jpg
assert_equal @attachment.styles[:ashash].format, :png assert_equal @attachment.styles[:ashash].format, :png
assert_equal @attachment.styles[:asstring].format, :png assert_equal @attachment.styles[:asstring].format, :png
......
require './test/helper' require 'spec_helper'
class Paperclip::TempfileFactoryTest < Test::Unit::TestCase describe Paperclip::TempfileFactory do
should "be able to generate a tempfile with the right name" do it "be able to generate a tempfile with the right name" do
file = subject.generate("omg.png") file = subject.generate("omg.png")
assert File.extname(file.path), "png" assert File.extname(file.path), "png"
end end
should "be able to generate a tempfile with the right name with a tilde at the beginning" do it "be able to generate a tempfile with the right name with a tilde at the beginning" do
file = subject.generate("~omg.png") file = subject.generate("~omg.png")
assert File.extname(file.path), "png" assert File.extname(file.path), "png"
end end
should "be able to generate a tempfile with the right name with a tilde at the end" do it "be able to generate a tempfile with the right name with a tilde at the end" do
file = subject.generate("omg.png~") file = subject.generate("omg.png~")
assert File.extname(file.path), "png" assert File.extname(file.path), "png"
end end
should "be able to generate a tempfile from a file with a really long name" do it "be able to generate a tempfile from a file with a really long name" do
filename = "#{"longfilename" * 100}.png" filename = "#{"longfilename" * 100}.png"
file = subject.generate(filename) file = subject.generate(filename)
assert File.extname(file.path), "png" assert File.extname(file.path), "png"
end end
should 'be able to take nothing as a parameter and not error' do it 'be able to take nothing as a parameter and not error' do
file = subject.generate file = subject.generate
assert File.exists?(file.path) assert File.exists?(file.path)
end end
......
# encoding: utf-8 # encoding: utf-8
require './test/helper' require 'spec_helper'
require 'paperclip/url_generator'
class UrlGeneratorTest < Test::Unit::TestCase describe Paperclip::UrlGenerator do
should "use the given interpolator" do it "use the given interpolator" do
expected = "the expected result" expected = "the expected result"
mock_attachment = MockAttachment.new mock_attachment = MockAttachment.new
mock_interpolator = MockInterpolator.new(:result => expected) mock_interpolator = MockInterpolator.new(:result => expected)
...@@ -17,7 +16,7 @@ class UrlGeneratorTest < Test::Unit::TestCase ...@@ -17,7 +16,7 @@ class UrlGeneratorTest < Test::Unit::TestCase
assert mock_interpolator.has_interpolated_style_name?(:style_name) assert mock_interpolator.has_interpolated_style_name?(:style_name)
end end
should "use the default URL when no file is assigned" do it "use the default URL when no file is assigned" do
mock_attachment = MockAttachment.new mock_attachment = MockAttachment.new
mock_interpolator = MockInterpolator.new mock_interpolator = MockInterpolator.new
default_url = "the default url" default_url = "the default url"
...@@ -30,7 +29,7 @@ class UrlGeneratorTest < Test::Unit::TestCase ...@@ -30,7 +29,7 @@ class UrlGeneratorTest < Test::Unit::TestCase
"expected the interpolator to be passed #{default_url.inspect} but it wasn't" "expected the interpolator to be passed #{default_url.inspect} but it wasn't"
end end
should "execute the default URL lambda when no file is assigned" do it "execute the default URL lambda when no file is assigned" do
mock_attachment = MockAttachment.new mock_attachment = MockAttachment.new
mock_interpolator = MockInterpolator.new mock_interpolator = MockInterpolator.new
default_url = lambda {|attachment| "the #{attachment.class.name} default url" } default_url = lambda {|attachment| "the #{attachment.class.name} default url" }
...@@ -43,7 +42,7 @@ class UrlGeneratorTest < Test::Unit::TestCase ...@@ -43,7 +42,7 @@ class UrlGeneratorTest < Test::Unit::TestCase
%{expected the interpolator to be passed "the MockAttachment default url", but it wasn't} %{expected the interpolator to be passed "the MockAttachment default url", but it wasn't}
end end
should "execute the method named by the symbol as the default URL when no file is assigned" do it "execute the method named by the symbol as the default URL when no file is assigned" do
mock_model = MockModel.new mock_model = MockModel.new
mock_attachment = MockAttachment.new(:model => mock_model) mock_attachment = MockAttachment.new(:model => mock_model)
mock_interpolator = MockInterpolator.new mock_interpolator = MockInterpolator.new
...@@ -57,7 +56,7 @@ class UrlGeneratorTest < Test::Unit::TestCase ...@@ -57,7 +56,7 @@ class UrlGeneratorTest < Test::Unit::TestCase
%{expected the interpolator to be passed #{mock_model.to_s}, but it wasn't} %{expected the interpolator to be passed #{mock_model.to_s}, but it wasn't}
end end
should "URL-escape spaces if asked to" do it "URL-escape spaces if asked to" do
expected = "the expected result" expected = "the expected result"
mock_attachment = MockAttachment.new mock_attachment = MockAttachment.new
mock_interpolator = MockInterpolator.new(:result => expected) mock_interpolator = MockInterpolator.new(:result => expected)
...@@ -69,7 +68,7 @@ class UrlGeneratorTest < Test::Unit::TestCase ...@@ -69,7 +68,7 @@ class UrlGeneratorTest < Test::Unit::TestCase
assert_equal "the%20expected%20result", result assert_equal "the%20expected%20result", result
end end
should "escape the result of the interpolator using a method on the object, if asked to escape" do it "escape the result of the interpolator using a method on the object, if asked to escape" do
expected = Class.new do expected = Class.new do
def escape def escape
"the escaped result" "the escaped result"
...@@ -85,7 +84,7 @@ class UrlGeneratorTest < Test::Unit::TestCase ...@@ -85,7 +84,7 @@ class UrlGeneratorTest < Test::Unit::TestCase
assert_equal "the escaped result", result assert_equal "the escaped result", result
end end
should "leave spaces unescaped as asked to" do it "leave spaces unescaped as asked to" do
expected = "the expected result" expected = "the expected result"
mock_attachment = MockAttachment.new mock_attachment = MockAttachment.new
mock_interpolator = MockInterpolator.new(:result => expected) mock_interpolator = MockInterpolator.new(:result => expected)
...@@ -97,7 +96,7 @@ class UrlGeneratorTest < Test::Unit::TestCase ...@@ -97,7 +96,7 @@ class UrlGeneratorTest < Test::Unit::TestCase
assert_equal "the expected result", result assert_equal "the expected result", result
end end
should "default to leaving spaces unescaped" do it "default to leaving spaces unescaped" do
expected = "the expected result" expected = "the expected result"
mock_attachment = MockAttachment.new mock_attachment = MockAttachment.new
mock_interpolator = MockInterpolator.new(:result => expected) mock_interpolator = MockInterpolator.new(:result => expected)
...@@ -109,7 +108,7 @@ class UrlGeneratorTest < Test::Unit::TestCase ...@@ -109,7 +108,7 @@ class UrlGeneratorTest < Test::Unit::TestCase
assert_equal "the expected result", result assert_equal "the expected result", result
end end
should "produce URLs without the updated_at value when the object does not respond to updated_at" do it "produce URLs without the updated_at value when the object does not respond to updated_at" do
expected = "the expected result" expected = "the expected result"
mock_interpolator = MockInterpolator.new(:result => expected) mock_interpolator = MockInterpolator.new(:result => expected)
mock_attachment = MockAttachment.new(:responds_to_updated_at => false) mock_attachment = MockAttachment.new(:responds_to_updated_at => false)
...@@ -121,7 +120,7 @@ class UrlGeneratorTest < Test::Unit::TestCase ...@@ -121,7 +120,7 @@ class UrlGeneratorTest < Test::Unit::TestCase
assert_equal expected, result assert_equal expected, result
end end
should "produce URLs without the updated_at value when the updated_at value is nil" do it "produce URLs without the updated_at value when the updated_at value is nil" do
expected = "the expected result" expected = "the expected result"
mock_interpolator = MockInterpolator.new(:result => expected) mock_interpolator = MockInterpolator.new(:result => expected)
mock_attachment = MockAttachment.new(:responds_to_updated_at => true, :updated_at => nil) mock_attachment = MockAttachment.new(:responds_to_updated_at => true, :updated_at => nil)
...@@ -133,7 +132,7 @@ class UrlGeneratorTest < Test::Unit::TestCase ...@@ -133,7 +132,7 @@ class UrlGeneratorTest < Test::Unit::TestCase
assert_equal expected, result assert_equal expected, result
end end
should "produce URLs with the updated_at when it exists" do it "produce URLs with the updated_at when it exists" do
expected = "the expected result" expected = "the expected result"
updated_at = 1231231234 updated_at = 1231231234
mock_interpolator = MockInterpolator.new(:result => expected) mock_interpolator = MockInterpolator.new(:result => expected)
...@@ -146,7 +145,7 @@ class UrlGeneratorTest < Test::Unit::TestCase ...@@ -146,7 +145,7 @@ class UrlGeneratorTest < Test::Unit::TestCase
assert_equal "#{expected}?#{updated_at}", result assert_equal "#{expected}?#{updated_at}", result
end end
should "produce URLs with the updated_at when it exists, separated with a & if a ? follow by = already exists" do it "produce URLs with the updated_at when it exists, separated with a & if a ? follow by = already exists" do
expected = "the?expected=result" expected = "the?expected=result"
updated_at = 1231231234 updated_at = 1231231234
mock_interpolator = MockInterpolator.new(:result => expected) mock_interpolator = MockInterpolator.new(:result => expected)
...@@ -159,7 +158,7 @@ class UrlGeneratorTest < Test::Unit::TestCase ...@@ -159,7 +158,7 @@ class UrlGeneratorTest < Test::Unit::TestCase
assert_equal "#{expected}&#{updated_at}", result assert_equal "#{expected}&#{updated_at}", result
end end
should "produce URLs without the updated_at when told to do as much" do it "produce URLs without the updated_at when told to do as much" do
expected = "the expected result" expected = "the expected result"
updated_at = 1231231234 updated_at = 1231231234
mock_interpolator = MockInterpolator.new(:result => expected) mock_interpolator = MockInterpolator.new(:result => expected)
...@@ -172,7 +171,7 @@ class UrlGeneratorTest < Test::Unit::TestCase ...@@ -172,7 +171,7 @@ class UrlGeneratorTest < Test::Unit::TestCase
assert_equal expected, result assert_equal expected, result
end end
should "produce the correct URL when the instance has a file name" do it "produce the correct URL when the instance has a file name" do
expected = "the expected result" expected = "the expected result"
mock_attachment = MockAttachment.new(:original_filename => 'exists') mock_attachment = MockAttachment.new(:original_filename => 'exists')
mock_interpolator = MockInterpolator.new mock_interpolator = MockInterpolator.new
......
require './test/helper' require 'spec_helper'
class AttachmentFileNameValidatorTest < Test::Unit::TestCase describe Paperclip::Validators::AttachmentFileNameValidator do
def setup before do
rebuild_model rebuild_model
@dummy = Dummy.new @dummy = Dummy.new
super
end end
def build_validator(options) def build_validator(options)
...@@ -14,24 +13,23 @@ class AttachmentFileNameValidatorTest < Test::Unit::TestCase ...@@ -14,24 +13,23 @@ class AttachmentFileNameValidatorTest < Test::Unit::TestCase
end end
context "with a failing validation" do context "with a failing validation" do
setup do before do
build_validator :matches => /.*\.png$/, :allow_nil => false build_validator :matches => /.*\.png$/, :allow_nil => false
@dummy.stubs(:avatar_file_name => "data.txt") @dummy.stubs(:avatar_file_name => "data.txt")
@validator.validate(@dummy) @validator.validate(@dummy)
end end
should "add error to the base object" do it "add error to the base object" do
assert @dummy.errors[:avatar].present?, assert @dummy.errors[:avatar].present?,
"Error not added to base attribute" "Error not added to base attribute"
end end
should "add error to base object as a string" do it "add error to base object as a string" do
assert_kind_of String, @dummy.errors[:avatar].first, expect(@dummy.errors[:avatar].first).to be_a String
"Error added to base attribute as something other than a String"
end end
end end
should "not add error to the base object with a successful validation" do it "not add error to the base object with a successful validation" do
build_validator :matches => /.*\.png$/, :allow_nil => false build_validator :matches => /.*\.png$/, :allow_nil => false
@dummy.stubs(:avatar_file_name => "image.png") @dummy.stubs(:avatar_file_name => "image.png")
@validator.validate(@dummy) @validator.validate(@dummy)
...@@ -42,46 +40,46 @@ class AttachmentFileNameValidatorTest < Test::Unit::TestCase ...@@ -42,46 +40,46 @@ class AttachmentFileNameValidatorTest < Test::Unit::TestCase
context "whitelist format" do context "whitelist format" do
context "with an allowed type" do context "with an allowed type" do
context "as a single regexp" do context "as a single regexp" do
setup do before do
build_validator :matches => /.*\.jpg$/ build_validator :matches => /.*\.jpg$/
@dummy.stubs(:avatar_file_name => "image.jpg") @dummy.stubs(:avatar_file_name => "image.jpg")
@validator.validate(@dummy) @validator.validate(@dummy)
end end
should "not set an error message" do it "not set an error message" do
assert @dummy.errors[:avatar_file_name].blank? assert @dummy.errors[:avatar_file_name].blank?
end end
end end
context "as a list" do context "as a list" do
setup do before do
build_validator :matches => [/.*\.png$/, /.*\.jpe?g$/] build_validator :matches => [/.*\.png$/, /.*\.jpe?g$/]
@dummy.stubs(:avatar_file_name => "image.jpg") @dummy.stubs(:avatar_file_name => "image.jpg")
@validator.validate(@dummy) @validator.validate(@dummy)
end end
should "not set an error message" do it "not set an error message" do
assert @dummy.errors[:avatar_file_name].blank? assert @dummy.errors[:avatar_file_name].blank?
end end
end end
end end
context "with a disallowed type" do context "with a disallowed type" do
should "set a correct default error message" do it "set a correct default error message" do
build_validator :matches => /^text\/.*/ build_validator :matches => /^text\/.*/
@dummy.stubs(:avatar_file_name => "image.jpg") @dummy.stubs(:avatar_file_name => "image.jpg")
@validator.validate(@dummy) @validator.validate(@dummy)
assert @dummy.errors[:avatar_file_name].present? assert @dummy.errors[:avatar_file_name].present?
assert_includes @dummy.errors[:avatar_file_name], "is invalid" expect(@dummy.errors[:avatar_file_name]).to include "is invalid"
end end
should "set a correct custom error message" do it "set a correct custom error message" do
build_validator :matches => /.*\.png$/, :message => "should be a PNG image" build_validator :matches => /.*\.png$/, :message => "should be a PNG image"
@dummy.stubs(:avatar_file_name => "image.jpg") @dummy.stubs(:avatar_file_name => "image.jpg")
@validator.validate(@dummy) @validator.validate(@dummy)
assert_includes @dummy.errors[:avatar_file_name], "should be a PNG image" expect(@dummy.errors[:avatar_file_name]).to include "should be a PNG image"
end end
end end
end end
...@@ -89,72 +87,72 @@ class AttachmentFileNameValidatorTest < Test::Unit::TestCase ...@@ -89,72 +87,72 @@ class AttachmentFileNameValidatorTest < Test::Unit::TestCase
context "blacklist format" do context "blacklist format" do
context "with an allowed type" do context "with an allowed type" do
context "as a single regexp" do context "as a single regexp" do
setup do before do
build_validator :not => /^text\/.*/ build_validator :not => /^text\/.*/
@dummy.stubs(:avatar_file_name => "image.jpg") @dummy.stubs(:avatar_file_name => "image.jpg")
@validator.validate(@dummy) @validator.validate(@dummy)
end end
should "not set an error message" do it "not set an error message" do
assert @dummy.errors[:avatar_file_name].blank? assert @dummy.errors[:avatar_file_name].blank?
end end
end end
context "as a list" do context "as a list" do
setup do before do
build_validator :not => [/.*\.png$/, /.*\.jpe?g$/] build_validator :not => [/.*\.png$/, /.*\.jpe?g$/]
@dummy.stubs(:avatar_file_name => "image.gif") @dummy.stubs(:avatar_file_name => "image.gif")
@validator.validate(@dummy) @validator.validate(@dummy)
end end
should "not set an error message" do it "not set an error message" do
assert @dummy.errors[:avatar_file_name].blank? assert @dummy.errors[:avatar_file_name].blank?
end end
end end
end end
context "with a disallowed type" do context "with a disallowed type" do
should "set a correct default error message" do it "set a correct default error message" do
build_validator :not => /data.*/ build_validator :not => /data.*/
@dummy.stubs(:avatar_file_name => "data.txt") @dummy.stubs(:avatar_file_name => "data.txt")
@validator.validate(@dummy) @validator.validate(@dummy)
assert @dummy.errors[:avatar_file_name].present? assert @dummy.errors[:avatar_file_name].present?
assert_includes @dummy.errors[:avatar_file_name], "is invalid" expect(@dummy.errors[:avatar_file_name]).to include "is invalid"
end end
should "set a correct custom error message" do it "set a correct custom error message" do
build_validator :not => /.*\.png$/, :message => "should not be a PNG image" build_validator :not => /.*\.png$/, :message => "should not be a PNG image"
@dummy.stubs(:avatar_file_name => "image.png") @dummy.stubs(:avatar_file_name => "image.png")
@validator.validate(@dummy) @validator.validate(@dummy)
assert_includes @dummy.errors[:avatar_file_name], "should not be a PNG image" expect(@dummy.errors[:avatar_file_name]).to include "should not be a PNG image"
end end
end end
end end
context "using the helper" do context "using the helper" do
setup do before do
Dummy.validates_attachment_file_name :avatar, :matches => /.*\.jpg$/ Dummy.validates_attachment_file_name :avatar, :matches => /.*\.jpg$/
end end
should "add the validator to the class" do it "add the validator to the class" do
assert Dummy.validators_on(:avatar).any?{ |validator| validator.kind == :attachment_file_name } assert Dummy.validators_on(:avatar).any?{ |validator| validator.kind == :attachment_file_name }
end end
end end
context "given options" do context "given options" do
should "raise argument error if no required argument was given" do it "raise argument error if no required argument was given" do
assert_raises(ArgumentError) do assert_raises(ArgumentError) do
build_validator :message => "Some message" build_validator :message => "Some message"
end end
end end
should "not raise argument error if :matches was given" do it "not raise argument error if :matches was given" do
build_validator :matches => /.*\.jpg$/ build_validator :matches => /.*\.jpg$/
end end
should "not raise argument error if :not was given" do it "not raise argument error if :not was given" do
build_validator :not => /.*\.jpg$/ build_validator :not => /.*\.jpg$/
end end
end end
......
require './test/helper' require 'spec_helper'
class AttachmentPresenceValidatorTest < Test::Unit::TestCase describe Paperclip::Validators::AttachmentPresenceValidator do
def setup before do
rebuild_model rebuild_model
@dummy = Dummy.new @dummy = Dummy.new
end end
...@@ -13,44 +13,44 @@ class AttachmentPresenceValidatorTest < Test::Unit::TestCase ...@@ -13,44 +13,44 @@ class AttachmentPresenceValidatorTest < Test::Unit::TestCase
end end
context "nil attachment" do context "nil attachment" do
setup do before do
@dummy.avatar = nil @dummy.avatar = nil
end end
context "with default options" do context "with default options" do
setup do before do
build_validator build_validator
@validator.validate(@dummy) @validator.validate(@dummy)
end end
should "add error on the attachment" do it "add error on the attachment" do
assert @dummy.errors[:avatar].present? assert @dummy.errors[:avatar].present?
end end
should "not add an error on the file_name attribute" do it "not add an error on the file_name attribute" do
assert @dummy.errors[:avatar_file_name].blank? assert @dummy.errors[:avatar_file_name].blank?
end end
end end
context "with :if option" do context "with :if option" do
context "returning true" do context "returning true" do
setup do before do
build_validator :if => true build_validator :if => true
@validator.validate(@dummy) @validator.validate(@dummy)
end end
should "perform a validation" do it "perform a validation" do
assert @dummy.errors[:avatar].present? assert @dummy.errors[:avatar].present?
end end
end end
context "returning false" do context "returning false" do
setup do before do
build_validator :if => false build_validator :if => false
@validator.validate(@dummy) @validator.validate(@dummy)
end end
should "perform a validation" do it "perform a validation" do
assert @dummy.errors[:avatar].present? assert @dummy.errors[:avatar].present?
end end
end end
...@@ -58,27 +58,27 @@ class AttachmentPresenceValidatorTest < Test::Unit::TestCase ...@@ -58,27 +58,27 @@ class AttachmentPresenceValidatorTest < Test::Unit::TestCase
end end
context "with attachment" do context "with attachment" do
setup do before do
build_validator build_validator
@dummy.avatar = StringIO.new('.\n') @dummy.avatar = StringIO.new('.\n')
@validator.validate(@dummy) @validator.validate(@dummy)
end end
should "not add error on the attachment" do it "not add error on the attachment" do
assert @dummy.errors[:avatar].blank? assert @dummy.errors[:avatar].blank?
end end
should "not add an error on the file_name attribute" do it "not add an error on the file_name attribute" do
assert @dummy.errors[:avatar_file_name].blank? assert @dummy.errors[:avatar_file_name].blank?
end end
end end
context "using the helper" do context "using the helper" do
setup do before do
Dummy.validates_attachment_presence :avatar Dummy.validates_attachment_presence :avatar
end end
should "add the validator to the class" do it "add the validator to the class" do
assert Dummy.validators_on(:avatar).any?{ |validator| validator.kind == :attachment_presence } assert Dummy.validators_on(:avatar).any?{ |validator| validator.kind == :attachment_presence }
end end
end end
......
require './test/helper' require 'spec_helper'
class AttachmentSizeValidatorTest < Test::Unit::TestCase describe Paperclip::Validators::AttachmentSizeValidator do
def setup before do
rebuild_model rebuild_model
@dummy = Dummy.new @dummy = Dummy.new
end end
...@@ -14,14 +14,14 @@ class AttachmentSizeValidatorTest < Test::Unit::TestCase ...@@ -14,14 +14,14 @@ class AttachmentSizeValidatorTest < Test::Unit::TestCase
def self.should_allow_attachment_file_size(size) def self.should_allow_attachment_file_size(size)
context "when the attachment size is #{size}" do context "when the attachment size is #{size}" do
should "add error to dummy object" do it "add error to dummy object" do
@dummy.stubs(:avatar_file_size).returns(size) @dummy.stubs(:avatar_file_size).returns(size)
@validator.validate(@dummy) @validator.validate(@dummy)
assert @dummy.errors[:avatar_file_size].blank?, assert @dummy.errors[:avatar_file_size].blank?,
"Expect an error message on :avatar_file_size, got none." "Expect an error message on :avatar_file_size, got none."
end end
should "not add error to the base dummy object" do it "not add error to the base dummy object" do
assert @dummy.errors[:avatar].blank?, assert @dummy.errors[:avatar].blank?,
"Error added to base attribute" "Error added to base attribute"
end end
...@@ -30,29 +30,28 @@ class AttachmentSizeValidatorTest < Test::Unit::TestCase ...@@ -30,29 +30,28 @@ class AttachmentSizeValidatorTest < Test::Unit::TestCase
def self.should_not_allow_attachment_file_size(size, options = {}) def self.should_not_allow_attachment_file_size(size, options = {})
context "when the attachment size is #{size}" do context "when the attachment size is #{size}" do
setup do before do
@dummy.stubs(:avatar_file_size).returns(size) @dummy.stubs(:avatar_file_size).returns(size)
@validator.validate(@dummy) @validator.validate(@dummy)
end end
should "add error to dummy object" do it "add error to dummy object" do
assert @dummy.errors[:avatar_file_size].present?, assert @dummy.errors[:avatar_file_size].present?,
"Unexpected error message on :avatar_file_size" "Unexpected error message on :avatar_file_size"
end end
should "add error to the base dummy object" do it "add error to the base dummy object" do
assert @dummy.errors[:avatar].present?, assert @dummy.errors[:avatar].present?,
"Error not added to base attribute" "Error not added to base attribute"
end end
should "add error to base object as a string" do it "add error to base object as a string" do
assert_kind_of String, @dummy.errors[:avatar].first, expect(@dummy.errors[:avatar].first).to be_a String
"Error added to base attribute as something other than a String"
end end
if options[:message] if options[:message]
should "return a correct error message" do it "return a correct error message" do
assert_includes @dummy.errors[:avatar_file_size], options[:message] expect(@dummy.errors[:avatar_file_size]).to include options[:message]
end end
end end
end end
...@@ -60,7 +59,7 @@ class AttachmentSizeValidatorTest < Test::Unit::TestCase ...@@ -60,7 +59,7 @@ class AttachmentSizeValidatorTest < Test::Unit::TestCase
context "with :in option" do context "with :in option" do
context "as a range" do context "as a range" do
setup do before do
build_validator :in => (5.kilobytes..10.kilobytes) build_validator :in => (5.kilobytes..10.kilobytes)
end end
...@@ -70,7 +69,7 @@ class AttachmentSizeValidatorTest < Test::Unit::TestCase ...@@ -70,7 +69,7 @@ class AttachmentSizeValidatorTest < Test::Unit::TestCase
end end
context "as a proc" do context "as a proc" do
setup do before do
build_validator :in => lambda { |avatar| (5.kilobytes..10.kilobytes) } build_validator :in => lambda { |avatar| (5.kilobytes..10.kilobytes) }
end end
...@@ -82,7 +81,7 @@ class AttachmentSizeValidatorTest < Test::Unit::TestCase ...@@ -82,7 +81,7 @@ class AttachmentSizeValidatorTest < Test::Unit::TestCase
context "with :greater_than option" do context "with :greater_than option" do
context "as number" do context "as number" do
setup do before do
build_validator :greater_than => 10.kilobytes build_validator :greater_than => 10.kilobytes
end end
...@@ -91,7 +90,7 @@ class AttachmentSizeValidatorTest < Test::Unit::TestCase ...@@ -91,7 +90,7 @@ class AttachmentSizeValidatorTest < Test::Unit::TestCase
end end
context "as a proc" do context "as a proc" do
setup do before do
build_validator :greater_than => lambda { |avatar| 10.kilobytes } build_validator :greater_than => lambda { |avatar| 10.kilobytes }
end end
...@@ -102,7 +101,7 @@ class AttachmentSizeValidatorTest < Test::Unit::TestCase ...@@ -102,7 +101,7 @@ class AttachmentSizeValidatorTest < Test::Unit::TestCase
context "with :less_than option" do context "with :less_than option" do
context "as number" do context "as number" do
setup do before do
build_validator :less_than => 10.kilobytes build_validator :less_than => 10.kilobytes
end end
...@@ -111,7 +110,7 @@ class AttachmentSizeValidatorTest < Test::Unit::TestCase ...@@ -111,7 +110,7 @@ class AttachmentSizeValidatorTest < Test::Unit::TestCase
end end
context "as a proc" do context "as a proc" do
setup do before do
build_validator :less_than => lambda { |avatar| 10.kilobytes } build_validator :less_than => lambda { |avatar| 10.kilobytes }
end end
...@@ -122,7 +121,7 @@ class AttachmentSizeValidatorTest < Test::Unit::TestCase ...@@ -122,7 +121,7 @@ class AttachmentSizeValidatorTest < Test::Unit::TestCase
context "with :greater_than and :less_than option" do context "with :greater_than and :less_than option" do
context "as numbers" do context "as numbers" do
setup do before do
build_validator :greater_than => 5.kilobytes, build_validator :greater_than => 5.kilobytes,
:less_than => 10.kilobytes :less_than => 10.kilobytes
end end
...@@ -133,7 +132,7 @@ class AttachmentSizeValidatorTest < Test::Unit::TestCase ...@@ -133,7 +132,7 @@ class AttachmentSizeValidatorTest < Test::Unit::TestCase
end end
context "as a proc" do context "as a proc" do
setup do before do
build_validator :greater_than => lambda { |avatar| 5.kilobytes }, build_validator :greater_than => lambda { |avatar| 5.kilobytes },
:less_than => lambda { |avatar| 10.kilobytes } :less_than => lambda { |avatar| 10.kilobytes }
end end
...@@ -146,7 +145,7 @@ class AttachmentSizeValidatorTest < Test::Unit::TestCase ...@@ -146,7 +145,7 @@ class AttachmentSizeValidatorTest < Test::Unit::TestCase
context "with :message option" do context "with :message option" do
context "given a range" do context "given a range" do
setup do before do
build_validator :in => (5.kilobytes..10.kilobytes), build_validator :in => (5.kilobytes..10.kilobytes),
:message => "is invalid. (Between %{min} and %{max} please.)" :message => "is invalid. (Between %{min} and %{max} please.)"
end end
...@@ -156,7 +155,7 @@ class AttachmentSizeValidatorTest < Test::Unit::TestCase ...@@ -156,7 +155,7 @@ class AttachmentSizeValidatorTest < Test::Unit::TestCase
end end
context "given :less_than and :greater_than" do context "given :less_than and :greater_than" do
setup do before do
build_validator :less_than => 10.kilobytes, build_validator :less_than => 10.kilobytes,
:greater_than => 5.kilobytes, :greater_than => 5.kilobytes,
:message => "is invalid. (Between %{min} and %{max} please.)" :message => "is invalid. (Between %{min} and %{max} please.)"
...@@ -169,7 +168,7 @@ class AttachmentSizeValidatorTest < Test::Unit::TestCase ...@@ -169,7 +168,7 @@ class AttachmentSizeValidatorTest < Test::Unit::TestCase
context "default error messages" do context "default error messages" do
context "given :less_than and :greater_than" do context "given :less_than and :greater_than" do
setup do before do
build_validator :greater_than => 5.kilobytes, build_validator :greater_than => 5.kilobytes,
:less_than => 10.kilobytes :less_than => 10.kilobytes
end end
...@@ -181,7 +180,7 @@ class AttachmentSizeValidatorTest < Test::Unit::TestCase ...@@ -181,7 +180,7 @@ class AttachmentSizeValidatorTest < Test::Unit::TestCase
end end
context "given a size range" do context "given a size range" do
setup do before do
build_validator :in => (5.kilobytes..10.kilobytes) build_validator :in => (5.kilobytes..10.kilobytes)
end end
...@@ -193,29 +192,29 @@ class AttachmentSizeValidatorTest < Test::Unit::TestCase ...@@ -193,29 +192,29 @@ class AttachmentSizeValidatorTest < Test::Unit::TestCase
end end
context "using the helper" do context "using the helper" do
setup do before do
Dummy.validates_attachment_size :avatar, :in => (5.kilobytes..10.kilobytes) Dummy.validates_attachment_size :avatar, :in => (5.kilobytes..10.kilobytes)
end end
should "add the validator to the class" do it "add the validator to the class" do
assert Dummy.validators_on(:avatar).any?{ |validator| validator.kind == :attachment_size } assert Dummy.validators_on(:avatar).any?{ |validator| validator.kind == :attachment_size }
end end
end end
context "given options" do context "given options" do
should "raise argument error if no required argument was given" do it "raise argument error if no required argument was given" do
assert_raises(ArgumentError) do assert_raises(ArgumentError) do
build_validator :message => "Some message" build_validator :message => "Some message"
end end
end end
(Paperclip::Validators::AttachmentSizeValidator::AVAILABLE_CHECKS).each do |argument| (Paperclip::Validators::AttachmentSizeValidator::AVAILABLE_CHECKS).each do |argument|
should "not raise arguemnt error if #{argument} was given" do it "not raise arguemnt error if #{argument} was given" do
build_validator argument => 5.kilobytes build_validator argument => 5.kilobytes
end end
end end
should "not raise argument error if :in was given" do it "not raise argument error if :in was given" do
build_validator :in => (5.kilobytes..10.kilobytes) build_validator :in => (5.kilobytes..10.kilobytes)
end end
end end
......
require './test/helper' require 'spec_helper'
class MediaTypeSpoofDetectionValidatorTest < Test::Unit::TestCase describe Paperclip::Validators::MediaTypeSpoofDetectionValidator do
def setup before do
rebuild_model rebuild_model
@dummy = Dummy.new @dummy = Dummy.new
end end
...@@ -12,11 +12,11 @@ class MediaTypeSpoofDetectionValidatorTest < Test::Unit::TestCase ...@@ -12,11 +12,11 @@ class MediaTypeSpoofDetectionValidatorTest < Test::Unit::TestCase
)) ))
end end
should "be on the attachment without being explicitly added" do it "be on the attachment without being explicitly added" do
assert Dummy.validators_on(:avatar).any?{ |validator| validator.kind == :media_type_spoof_detection } assert Dummy.validators_on(:avatar).any?{ |validator| validator.kind == :media_type_spoof_detection }
end end
should "return default error message for spoofed media type" do it "return default error message for spoofed media type" do
build_validator build_validator
file = File.new(fixture_file("5k.png"), "rb") file = File.new(fixture_file("5k.png"), "rb")
@dummy.avatar.assign(file) @dummy.avatar.assign(file)
...@@ -28,7 +28,7 @@ class MediaTypeSpoofDetectionValidatorTest < Test::Unit::TestCase ...@@ -28,7 +28,7 @@ class MediaTypeSpoofDetectionValidatorTest < Test::Unit::TestCase
assert_equal "has an extension that does not match its contents", @dummy.errors[:avatar].first assert_equal "has an extension that does not match its contents", @dummy.errors[:avatar].first
end end
should "run when attachment is dirty" do it "run when attachment is dirty" do
build_validator build_validator
file = File.new(fixture_file("5k.png"), "rb") file = File.new(fixture_file("5k.png"), "rb")
@dummy.avatar.assign(file) @dummy.avatar.assign(file)
...@@ -39,7 +39,7 @@ class MediaTypeSpoofDetectionValidatorTest < Test::Unit::TestCase ...@@ -39,7 +39,7 @@ class MediaTypeSpoofDetectionValidatorTest < Test::Unit::TestCase
assert_received(Paperclip::MediaTypeSpoofDetector, :using){|e| e.once } assert_received(Paperclip::MediaTypeSpoofDetector, :using){|e| e.once }
end end
should "not run when attachment is not dirty" do it "not run when attachment is not dirty" do
Paperclip::MediaTypeSpoofDetector.stubs(:using).never Paperclip::MediaTypeSpoofDetector.stubs(:using).never
@dummy.valid? @dummy.valid?
assert_received(Paperclip::MediaTypeSpoofDetector, :using){|e| e.never } assert_received(Paperclip::MediaTypeSpoofDetector, :using){|e| e.never }
......
require './test/helper' require 'spec_helper'
class ValidatorsTest < Test::Unit::TestCase
include ActiveSupport::Testing::Deprecation
def setup
rebuild_model
end
describe Paperclip::Validators do
context "using the helper" do context "using the helper" do
setup do before do
Dummy.validates_attachment :avatar, :presence => true, :content_type => { :content_type => "image/jpeg" }, :size => { :in => 0..10.kilobytes } Dummy.validates_attachment :avatar, :presence => true, :content_type => { :content_type => "image/jpeg" }, :size => { :in => 0..10240 }
end end
should "add the attachment_presence validator to the class" do it "adds the attachment_presence validator to the class" do
assert Dummy.validators_on(:avatar).any?{ |validator| validator.kind == :attachment_presence } assert Dummy.validators_on(:avatar).any?{ |validator| validator.kind == :attachment_presence }
end end
should "add the attachment_content_type validator to the class" do it "adds the attachment_content_type validator to the class" do
assert Dummy.validators_on(:avatar).any?{ |validator| validator.kind == :attachment_content_type } assert Dummy.validators_on(:avatar).any?{ |validator| validator.kind == :attachment_content_type }
end end
should "add the attachment_size validator to the class" do it "adds the attachment_size validator to the class" do
assert Dummy.validators_on(:avatar).any?{ |validator| validator.kind == :attachment_size } assert Dummy.validators_on(:avatar).any?{ |validator| validator.kind == :attachment_size }
end end
should 'prevent you from attaching a file that violates that validation' do it 'prevents you from attaching a file that violates that validation' do
Dummy.class_eval{ validate(:name) { raise "DO NOT RUN THIS" } } Dummy.class_eval{ validate(:name) { raise "DO NOT RUN THIS" } }
dummy = Dummy.new(:avatar => File.new(fixture_file("12k.png"))) dummy = Dummy.new(:avatar => File.new(fixture_file("12k.png")))
assert_equal [:avatar_content_type, :avatar, :avatar_file_size], dummy.errors.keys assert_equal [:avatar_content_type, :avatar, :avatar_file_size], dummy.errors.keys
assert_raise(RuntimeError){ dummy.valid? } assert_raises(RuntimeError){ dummy.valid? }
end end
end end
context "using the helper with a conditional" do context "using the helper with a conditional" do
setup do before do
rebuild_class
Dummy.validates_attachment :avatar, :presence => true, Dummy.validates_attachment :avatar, :presence => true,
:content_type => { :content_type => "image/jpeg" }, :content_type => { :content_type => "image/jpeg" },
:size => { :in => 0..10.kilobytes }, :size => { :in => 0..10240 },
:if => :title_present? :if => :title_present?
end end
should "validate the attachment if title is present" do it "validates the attachment if title is present" do
Dummy.class_eval do Dummy.class_eval do
def title_present? def title_present?
true true
...@@ -50,50 +45,50 @@ class ValidatorsTest < Test::Unit::TestCase ...@@ -50,50 +45,50 @@ class ValidatorsTest < Test::Unit::TestCase
assert_equal [:avatar_content_type, :avatar, :avatar_file_size], dummy.errors.keys assert_equal [:avatar_content_type, :avatar, :avatar_file_size], dummy.errors.keys
end end
should "not validate attachment if tile is not present" do it "does not validate attachment if title is not present" do
Dummy.class_eval do Dummy.class_eval do
def title_present? def title_present?
false false
end end
end end
dummy = Dummy.new(:avatar => File.new(fixture_file("12k.png"))) dummy = Dummy.new(avatar: File.new(fixture_file("12k.png")))
assert_equal [], dummy.errors.keys assert_equal [], dummy.errors.keys
end end
end end
context 'with no other validations on the Dummy#avatar attachment' do context 'with no other validations on the Dummy#avatar attachment' do
setup do before do
reset_class("Dummy") reset_class("Dummy")
Dummy.has_attached_file :avatar Dummy.has_attached_file :avatar
Paperclip.reset_duplicate_clash_check! Paperclip.reset_duplicate_clash_check!
end end
should 'raise an error when no content_type validation exists' do it 'raises an error when no content_type validation exists' do
assert_raises(Paperclip::Errors::MissingRequiredValidatorError) do assert_raises(Paperclip::Errors::MissingRequiredValidatorError) do
Dummy.new(:avatar => File.new(fixture_file("12k.png"))) Dummy.new(:avatar => File.new(fixture_file("12k.png")))
end end
end end
should 'not raise an error when a content_type validation exists' do it 'does not raise an error when a content_type validation exists' do
Dummy.validates_attachment :avatar, :content_type => { :content_type => "image/jpeg" } Dummy.validates_attachment :avatar, :content_type => { :content_type => "image/jpeg" }
assert_nothing_raised(Paperclip::Errors::MissingRequiredValidatorError) do assert_nothing_raised do
Dummy.new(:avatar => File.new(fixture_file("12k.png"))) Dummy.new(:avatar => File.new(fixture_file("12k.png")))
end end
end end
should 'not raise an error when a file_name validation exists' do it 'does not raise an error when a file_name validation exists' do
Dummy.validates_attachment :avatar, :file_name => { :matches => /png$/ } Dummy.validates_attachment :avatar, :file_name => { :matches => /png$/ }
assert_nothing_raised(Paperclip::Errors::MissingRequiredValidatorError) do assert_nothing_raised do
Dummy.new(:avatar => File.new(fixture_file("12k.png"))) Dummy.new(:avatar => File.new(fixture_file("12k.png")))
end end
end end
should 'not raise an error when a the validation has been explicitly rejected' do it 'does not raise an error when a the validation has been explicitly rejected' do
Dummy.validates_attachment :avatar, :file_type_ignorance => true Dummy.validates_attachment :avatar, :file_type_ignorance => true
assert_nothing_raised(Paperclip::Errors::MissingRequiredValidatorError) do assert_nothing_raised do
Dummy.new(:avatar => File.new(fixture_file("12k.png"))) Dummy.new(:avatar => File.new(fixture_file("12k.png")))
end end
end end
......
require 'rubygems' require 'rubygems'
require 'tempfile' require 'rspec'
require 'pathname'
require 'test/unit'
require 'active_record' require 'active_record'
require 'active_record/version' require 'active_record/version'
require 'active_support' require 'active_support'
require 'active_support/core_ext' require 'active_support/core_ext'
require 'shoulda' require 'mocha/api'
require 'mocha/setup'
require 'bourne' require 'bourne'
require 'shoulda/context'
require 'mime/types'
require 'pathname'
require 'ostruct' require 'ostruct'
begin
require 'pry'
rescue LoadError
# Pry is not available, just ignore.
end
puts "Testing against version #{ActiveRecord::VERSION::STRING}"
`ruby -e 'exit 0'` # Prime $? with a value.
begin
require 'ruby-debug'
rescue LoadError
puts "debugger disabled"
end
ROOT = Pathname(File.expand_path(File.join(File.dirname(__FILE__), '..'))) ROOT = Pathname(File.expand_path(File.join(File.dirname(__FILE__), '..')))
$previous_count = 0
class Test::Unit::TestCase
def setup
silence_warnings do
Object.const_set(:Rails, stub('Rails'))
Rails.stubs(:root).returns(Pathname.new(ROOT).join('tmp'))
Rails.stubs(:env).returns('test')
Rails.stubs(:const_defined?).with(:Railtie).returns(false)
ActiveSupport::Deprecation.silenced = true
end
end
def teardown
end
def report_files
files = []
ObjectSpace.each_object(IO){|io| files << io unless io.closed? }
if files.count > $previous_count
puts __name__
puts "#{files.count} files"
files.each do |file|
puts "Open IO: #{file.inspect}"
end
end
$previous_count = files.count
end
end
$LOAD_PATH << File.join(ROOT, 'lib') $LOAD_PATH << File.join(ROOT, 'lib')
$LOAD_PATH << File.join(ROOT, 'lib', 'paperclip') $LOAD_PATH << File.join(ROOT, 'lib', 'paperclip')
require File.join(ROOT, 'lib', 'paperclip.rb') require File.join(ROOT, 'lib', 'paperclip.rb')
require './shoulda_macros/paperclip'
FIXTURES_DIR = File.join(File.dirname(__FILE__), "fixtures") FIXTURES_DIR = File.join(File.dirname(__FILE__), "fixtures")
config = YAML::load(IO.read(File.dirname(__FILE__) + '/database.yml')) config = YAML::load(IO.read(File.dirname(__FILE__) + '/database.yml'))
ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + "/debug.log") ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + "/debug.log")
ActiveRecord::Base.establish_connection(config['test']) ActiveRecord::Base.establish_connection(config['test'])
Paperclip.options[:logger] = ActiveRecord::Base.logger Paperclip.options[:logger] = ActiveRecord::Base.logger
def using_protected_attributes? Dir[File.join(ROOT, 'spec', 'support', '**', '*.rb')].each{|f| require f }
ActiveRecord::VERSION::MAJOR < 4
end Rails = FakeRails.new('test', Pathname.new(ROOT).join('tmp'))
ActiveSupport::Deprecation.silenced = true
def require_everything_in_directory(directory_name) RSpec.configure do |config|
Dir[File.join(File.dirname(__FILE__), directory_name, '*')].each do |f| config.include Assertions
require f config.mock_framework = :mocha
config.before(:all) do
rebuild_model
end end
end end
require_everything_in_directory('support') def using_protected_attributes?
ActiveRecord::VERSION::MAJOR < 4
end
def reset_class class_name def reset_class class_name
ActiveRecord::Base.send(:include, Paperclip::Glue) ActiveRecord::Base.send(:include, Paperclip::Glue)
...@@ -171,22 +122,22 @@ ensure ...@@ -171,22 +122,22 @@ ensure
end end
def should_accept_dummy_class def should_accept_dummy_class
should "accept the class" do it "accepts the class" do
assert_accepts @matcher, Dummy expect(@matcher).to accept(Dummy)
end end
should "accept an instance of that class" do it "accepts an instance of that class" do
assert_accepts @matcher, Dummy.new expect(@matcher).to accept(Dummy.new)
end end
end end
def should_reject_dummy_class def should_reject_dummy_class
should "reject the class" do it "rejects the class" do
assert_rejects @matcher, Dummy expect(@matcher).to_not accept(Dummy)
end end
should "reject an instance of that class" do it "rejects an instance of that class" do
assert_rejects @matcher, Dummy.new expect(@matcher).to_not accept(Dummy.new)
end end
end end
......
module Assertions
def assert(truthy, message = nil)
expect(truthy).to(be_true, message)
end
def assert_equal(expected, actual, message = nil)
expect(actual).to(eq(expected), message)
end
def assert_not_equal(expected, actual, message = nil)
expect(actual).to_not(eq(expected), message)
end
def assert_raises(exception_class, message = nil, &block)
expect(&block).to raise_error(exception_class, message)
end
def assert_nothing_raised(&block)
expect(&block).to_not raise_error
end
def assert_nil(thing)
expect(thing).to be_nil
end
def assert_contains(haystack, needle)
expect(haystack).to include(needle)
end
def assert_match(pattern, value)
expect(value).to match(pattern)
end
def assert_no_match(pattern, value)
expect(value).to_not match(pattern)
end
def assert_file_exists(path_to_file)
expect(path_to_file).to exist
end
def assert_file_not_exists(path_to_file)
expect(path_to_file).to_not exist
end
def assert_empty(object)
expect(object).to be_empty
end
end
class FakeRails
def initialize(env, root)
@env = env
@root = root
end
attr_accessor :env, :root
def const_defined?(const)
false
end
end
RSpec::Matchers.define :accept do |expected|
match do |actual|
actual.matches?(expected)
end
end
RSpec::Matchers.define :exist do |expected|
match do |actual|
File.exists?(actual)
end
end
require './test/helper'
require 'rails/generators'
require 'generators/paperclip/paperclip_generator'
class GeneratorTest < Rails::Generators::TestCase
tests PaperclipGenerator
destination File.expand_path("../tmp", File.dirname(__FILE__))
setup :prepare_destination
context 'running migration' do
context 'with single attachment name' do
setup do
run_generator %w(user avatar)
end
should 'create a correct migration file' do
assert_migration 'db/migrate/add_attachment_avatar_to_users.rb' do |migration|
assert_match /class AddAttachmentAvatarToUsers/, migration
assert_class_method :up, migration do |up|
expected = <<-migration
change_table :users do |t|
t.attachment :avatar
end
migration
assert_equal expected.squish, up.squish
end
assert_class_method :down, migration do |down|
expected = <<-migration
drop_attached_file :users, :avatar
migration
assert_equal expected.squish, down.squish
end
end
end
end
context 'with multiple attachment names' do
setup do
run_generator %w(user avatar photo)
end
should 'create a correct migration file' do
assert_migration 'db/migrate/add_attachment_avatar_photo_to_users.rb' do |migration|
assert_match /class AddAttachmentAvatarPhotoToUsers/, migration
assert_class_method :up, migration do |up|
expected = <<-migration
change_table :users do |t|
t.attachment :avatar
t.attachment :photo
end
migration
assert_equal expected.squish, up.squish
end
assert_class_method :down, migration do |down|
expected = <<-migration
drop_attached_file :users, :avatar
drop_attached_file :users, :photo
migration
assert_equal expected.squish, down.squish
end
end
end
end
context 'without required arguments' do
should 'not create the migration' do
begin
silence_stream(STDERR) { run_generator %w() }
assert_no_migration 'db/migrate/add_attachment_avatar_to_users.rb'
rescue Thor::RequiredArgumentMissingError
# This is also OK. It happens in 1.9.2 and Rails 3.2
end
end
end
end
end
require './test/helper'
class HaveAttachedFileMatcherTest < Test::Unit::TestCase
context "have_attached_file" do
setup do
reset_class "Dummy"
reset_table "dummies"
@matcher = self.class.have_attached_file(:avatar)
end
context "given a class with no attachment" do
should_reject_dummy_class
end
context "given a class with an attachment" do
setup do
modify_table("dummies"){|d| d.string :avatar_file_name }
Dummy.has_attached_file :avatar
Dummy.do_not_validate_attachment_file_type :avatar
end
should_accept_dummy_class
end
end
end
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment