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,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 "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=>"../"
......
...@@ -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 describe 'Attachment Processing' do
def setup context 'using validates_attachment_content_type' do
rebuild_model before do
rebuild_class
end end
context 'using validates_attachment_content_type' do it 'process attachments given a valid assignment' do
should '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' })
......
# encoding: utf-8 # encoding: utf-8
require './test/helper' require 'spec_helper'
require 'paperclip/attachment'
class Dummy; end describe Paperclip::Attachment do
class AttachmentTest < Test::Unit::TestCase it "is not present when file not set" do
context "presence" do
setup do
rebuild_class rebuild_class
@dummy = Dummy.new dummy = Dummy.new
end expect(dummy.avatar).to be_blank
expect(dummy.avatar).to_not be_present
context "when file not set" do
should "not be present" do
assert @dummy.avatar.blank?
refute @dummy.avatar.present?
end
end end
context "when file set" do it "is present when the file is set" do
setup { @dummy.avatar = File.new(fixture_file("50x50.png"), "rb") } rebuild_class
dummy = Dummy.new
should "be present" do dummy.avatar = File.new(fixture_file("50x50.png"), "rb")
refute @dummy.avatar.blank? expect(dummy.avatar).to_not be_blank
assert @dummy.avatar.present? expect(dummy.avatar).to be_present
end
end
end end
should "process :original style first" do it "processes :original style first" do
file = File.new(fixture_file("50x50.png"), 'rb') file = File.new(fixture_file("50x50.png"), 'rb')
rebuild_class :styles => { :small => '100x>', :original => '42x42#' } rebuild_class :styles => { :small => '100x>', :original => '42x42#' }
dummy = Dummy.new dummy = Dummy.new
...@@ -37,12 +26,12 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -37,12 +26,12 @@ class AttachmentTest < Test::Unit::TestCase
dummy.save dummy.save
# :small avatar should be 42px wide (processed original), not 50px (preprocessed original) # :small avatar should be 42px wide (processed original), not 50px (preprocessed original)
assert_equal `identify -format "%w" "#{dummy.avatar.path(:small)}"`.strip, "42" expect(`identify -format "%w" "#{dummy.avatar.path(:small)}"`.strip).to eq "42"
file.close file.close
end end
should "not delete styles that don't get reprocessed" do it "not delete styles that don't get reprocessed" do
file = File.new(fixture_file("50x50.png"), 'rb') file = File.new(fixture_file("50x50.png"), 'rb')
rebuild_class :styles => { :small => '100x>', rebuild_class :styles => { :small => '100x>',
:large => '500x>', :large => '500x>',
...@@ -51,57 +40,56 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -51,57 +40,56 @@ class AttachmentTest < Test::Unit::TestCase
dummy.avatar = file dummy.avatar = file
dummy.save dummy.save
assert_file_exists(dummy.avatar.path(:small)) expect(dummy.avatar.path(:small)).to exist
assert_file_exists(dummy.avatar.path(:large)) expect(dummy.avatar.path(:large)).to exist
assert_file_exists(dummy.avatar.path(:original)) expect(dummy.avatar.path(:original)).to exist
dummy.avatar.reprocess!(:small) dummy.avatar.reprocess!(:small)
assert_file_exists(dummy.avatar.path(:small)) expect(dummy.avatar.path(:small)).to exist
assert_file_exists(dummy.avatar.path(:large)) expect(dummy.avatar.path(:large)).to exist
assert_file_exists(dummy.avatar.path(:original)) expect(dummy.avatar.path(:original)).to exist
end end
context "having a not empty hash as a default option" do context "having a not empty hash as a default option" do
setup do before do
@old_default_options = Paperclip::Attachment.default_options.dup @old_default_options = Paperclip::Attachment.default_options.dup
@new_default_options = { :convert_options => { :all => "-background white" } } @new_default_options = { :convert_options => { :all => "-background white" } }
Paperclip::Attachment.default_options.merge!(@new_default_options) Paperclip::Attachment.default_options.merge!(@new_default_options)
end end
teardown do after do
Paperclip::Attachment.default_options.merge!(@old_default_options) Paperclip::Attachment.default_options.merge!(@old_default_options)
end end
should "deep merge when it is overridden" do it "deep merge when it is overridden" do
new_options = { :convert_options => { :thumb => "-thumbnailize" } } new_options = { :convert_options => { :thumb => "-thumbnailize" } }
attachment = Paperclip::Attachment.new(:name, :instance, new_options) attachment = Paperclip::Attachment.new(:name, :instance, new_options)
assert_equal Paperclip::Attachment.default_options.deep_merge(new_options), expect(Paperclip::Attachment.default_options.deep_merge(new_options)).to eq attachment.instance_variable_get("@options")
attachment.instance_variable_get("@options")
end end
end end
should "handle a boolean second argument to #url" do it "handles a boolean second argument to #url" do
mock_url_generator_builder = MockUrlGeneratorBuilder.new mock_url_generator_builder = MockUrlGeneratorBuilder.new
attachment = Paperclip::Attachment.new(:name, :instance, :url_generator => mock_url_generator_builder) attachment = Paperclip::Attachment.new(:name, :instance, :url_generator => mock_url_generator_builder)
attachment.url(:style_name, true) attachment.url(:style_name, true)
assert mock_url_generator_builder.has_generated_url_with_options?(:timestamp => true, :escape => true) expect(mock_url_generator_builder.has_generated_url_with_options?(:timestamp => true, :escape => true)).to be_true
attachment.url(:style_name, false) attachment.url(:style_name, false)
assert mock_url_generator_builder.has_generated_url_with_options?(:timestamp => false, :escape => true) expect(mock_url_generator_builder.has_generated_url_with_options?(:timestamp => false, :escape => true)).to be_true
end end
should "pass the style and options through to the URL generator on #url" do it "pass the style and options through to the URL generator on #url" do
mock_url_generator_builder = MockUrlGeneratorBuilder.new mock_url_generator_builder = MockUrlGeneratorBuilder.new
attachment = Paperclip::Attachment.new(:name, :instance, :url_generator => mock_url_generator_builder) attachment = Paperclip::Attachment.new(:name, :instance, :url_generator => mock_url_generator_builder)
attachment.url(:style_name, :options => :values) attachment.url(:style_name, :options => :values)
assert mock_url_generator_builder.has_generated_url_with_options?(:options => :values) expect(mock_url_generator_builder.has_generated_url_with_options?(:options => :values)).to be_true
end end
should "pass default options through when #url is given one argument" do it "pass default options through when #url is given one argument" do
mock_url_generator_builder = MockUrlGeneratorBuilder.new mock_url_generator_builder = MockUrlGeneratorBuilder.new
attachment = Paperclip::Attachment.new(:name, attachment = Paperclip::Attachment.new(:name,
:instance, :instance,
...@@ -112,7 +100,7 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -112,7 +100,7 @@ class AttachmentTest < Test::Unit::TestCase
assert mock_url_generator_builder.has_generated_url_with_options?(:escape => true, :timestamp => true) assert mock_url_generator_builder.has_generated_url_with_options?(:escape => true, :timestamp => true)
end end
should "pass default style and options through when #url is given no arguments" do it "pass default style and options through when #url is given no arguments" do
mock_url_generator_builder = MockUrlGeneratorBuilder.new mock_url_generator_builder = MockUrlGeneratorBuilder.new
attachment = Paperclip::Attachment.new(:name, attachment = Paperclip::Attachment.new(:name,
:instance, :instance,
...@@ -125,7 +113,7 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -125,7 +113,7 @@ class AttachmentTest < Test::Unit::TestCase
assert mock_url_generator_builder.has_generated_url_with_style_name?('default style') assert mock_url_generator_builder.has_generated_url_with_style_name?('default style')
end end
should "pass the option :timestamp => true if :use_timestamp is true and :timestamp is not passed" do it "pass the option :timestamp => true if :use_timestamp is true and :timestamp is not passed" do
mock_url_generator_builder = MockUrlGeneratorBuilder.new mock_url_generator_builder = MockUrlGeneratorBuilder.new
attachment = Paperclip::Attachment.new(:name, attachment = Paperclip::Attachment.new(:name,
:instance, :instance,
...@@ -136,7 +124,7 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -136,7 +124,7 @@ class AttachmentTest < Test::Unit::TestCase
assert mock_url_generator_builder.has_generated_url_with_options?(:escape => true, :timestamp => true) assert mock_url_generator_builder.has_generated_url_with_options?(:escape => true, :timestamp => true)
end end
should "pass the option :timestamp => false if :use_timestamp is false and :timestamp is not passed" do it "pass the option :timestamp => false if :use_timestamp is false and :timestamp is not passed" do
mock_url_generator_builder = MockUrlGeneratorBuilder.new mock_url_generator_builder = MockUrlGeneratorBuilder.new
attachment = Paperclip::Attachment.new(:name, attachment = Paperclip::Attachment.new(:name,
:instance, :instance,
...@@ -147,7 +135,7 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -147,7 +135,7 @@ class AttachmentTest < Test::Unit::TestCase
assert mock_url_generator_builder.has_generated_url_with_options?(:escape => true, :timestamp => false) assert mock_url_generator_builder.has_generated_url_with_options?(:escape => true, :timestamp => false)
end end
should "not change the :timestamp if :timestamp is passed" do it "not change the :timestamp if :timestamp is passed" do
mock_url_generator_builder = MockUrlGeneratorBuilder.new mock_url_generator_builder = MockUrlGeneratorBuilder.new
attachment = Paperclip::Attachment.new(:name, attachment = Paperclip::Attachment.new(:name,
:instance, :instance,
...@@ -158,7 +146,7 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -158,7 +146,7 @@ class AttachmentTest < Test::Unit::TestCase
assert mock_url_generator_builder.has_generated_url_with_options?(:escape => true, :timestamp => true) assert mock_url_generator_builder.has_generated_url_with_options?(:escape => true, :timestamp => true)
end end
should "render JSON as default style" do it "render JSON as default style" do
mock_url_generator_builder = MockUrlGeneratorBuilder.new mock_url_generator_builder = MockUrlGeneratorBuilder.new
attachment = Paperclip::Attachment.new(:name, attachment = Paperclip::Attachment.new(:name,
:instance, :instance,
...@@ -169,7 +157,7 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -169,7 +157,7 @@ class AttachmentTest < Test::Unit::TestCase
assert mock_url_generator_builder.has_generated_url_with_style_name?('default style') assert mock_url_generator_builder.has_generated_url_with_style_name?('default style')
end end
should "pass the option :escape => true if :escape_url is true and :escape is not passed" do it "pass the option :escape => true if :escape_url is true and :escape is not passed" do
mock_url_generator_builder = MockUrlGeneratorBuilder.new mock_url_generator_builder = MockUrlGeneratorBuilder.new
attachment = Paperclip::Attachment.new(:name, attachment = Paperclip::Attachment.new(:name,
:instance, :instance,
...@@ -180,7 +168,7 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -180,7 +168,7 @@ class AttachmentTest < Test::Unit::TestCase
assert mock_url_generator_builder.has_generated_url_with_options?(:escape => true) assert mock_url_generator_builder.has_generated_url_with_options?(:escape => true)
end end
should "pass the option :escape => false if :escape_url is false and :escape is not passed" do it "pass the option :escape => false if :escape_url is false and :escape is not passed" do
mock_url_generator_builder = MockUrlGeneratorBuilder.new mock_url_generator_builder = MockUrlGeneratorBuilder.new
attachment = Paperclip::Attachment.new(:name, attachment = Paperclip::Attachment.new(:name,
:instance, :instance,
...@@ -191,7 +179,7 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -191,7 +179,7 @@ class AttachmentTest < Test::Unit::TestCase
assert mock_url_generator_builder.has_generated_url_with_options?(:escape => false) assert mock_url_generator_builder.has_generated_url_with_options?(:escape => false)
end end
should "return the path based on the url by default" do it "return the path based on the url by default" do
@attachment = attachment :url => "/:class/:id/:basename" @attachment = attachment :url => "/:class/:id/:basename"
@model = @attachment.instance @model = @attachment.instance
@model.id = 1234 @model.id = 1234
...@@ -199,7 +187,7 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -199,7 +187,7 @@ class AttachmentTest < Test::Unit::TestCase
assert_equal "#{Rails.root}/public/fake_models/1234/fake", @attachment.path assert_equal "#{Rails.root}/public/fake_models/1234/fake", @attachment.path
end end
should "default to a path that scales" do it "default to a path that scales" do
avatar_attachment = attachment avatar_attachment = attachment
model = avatar_attachment.instance model = avatar_attachment.instance
model.id = 1234 model.id = 1234
...@@ -208,7 +196,7 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -208,7 +196,7 @@ class AttachmentTest < Test::Unit::TestCase
assert_equal expected_path, avatar_attachment.path assert_equal expected_path, avatar_attachment.path
end end
should "render JSON as the URL to the attachment" do it "render JSON as the URL to the attachment" do
avatar_attachment = attachment avatar_attachment = attachment
model = avatar_attachment.instance model = avatar_attachment.instance
model.id = 1234 model.id = 1234
...@@ -216,7 +204,7 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -216,7 +204,7 @@ class AttachmentTest < Test::Unit::TestCase
assert_equal attachment.url, attachment.as_json assert_equal attachment.url, attachment.as_json
end end
should "render JSON from the model when requested by :methods" do it "render JSON from the model when requested by :methods" do
rebuild_model rebuild_model
dummy = Dummy.new dummy = Dummy.new
dummy.id = 1234 dummy.id = 1234
...@@ -230,7 +218,7 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -230,7 +218,7 @@ class AttachmentTest < Test::Unit::TestCase
end end
context "Attachment default_options" do context "Attachment default_options" do
setup do before do
rebuild_model rebuild_model
@old_default_options = Paperclip::Attachment.default_options.dup @old_default_options = Paperclip::Attachment.default_options.dup
@new_default_options = @old_default_options.merge({ @new_default_options = @old_default_options.merge({
...@@ -240,11 +228,11 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -240,11 +228,11 @@ class AttachmentTest < Test::Unit::TestCase
}) })
end end
teardown do after do
Paperclip::Attachment.default_options.merge! @old_default_options Paperclip::Attachment.default_options.merge! @old_default_options
end end
should "be overrideable" do it "be overrideable" do
Paperclip::Attachment.default_options.merge!(@new_default_options) Paperclip::Attachment.default_options.merge!(@new_default_options)
@new_default_options.keys.each do |key| @new_default_options.keys.each do |key|
assert_equal @new_default_options[key], assert_equal @new_default_options[key],
...@@ -253,41 +241,41 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -253,41 +241,41 @@ class AttachmentTest < Test::Unit::TestCase
end end
context "without an Attachment" do context "without an Attachment" do
setup do before do
@dummy = Dummy.new @dummy = Dummy.new
end end
should "return false when asked exists?" do it "return false when asked exists?" do
assert !@dummy.avatar.exists? assert !@dummy.avatar.exists?
end end
end end
context "on an Attachment" do context "on an Attachment" do
setup do before do
@dummy = Dummy.new @dummy = Dummy.new
@attachment = @dummy.avatar @attachment = @dummy.avatar
end end
Paperclip::Attachment.default_options.keys.each do |key| Paperclip::Attachment.default_options.keys.each do |key|
should "be the default_options for #{key}" do it "be the default_options for #{key}" do
assert_equal @old_default_options[key], assert_equal @old_default_options[key],
@attachment.instance_variable_get("@options")[key], @attachment.instance_variable_get("@options")[key],
key key.to_s
end end
end end
context "when redefined" do context "when redefined" do
setup do before do
Paperclip::Attachment.default_options.merge!(@new_default_options) Paperclip::Attachment.default_options.merge!(@new_default_options)
@dummy = Dummy.new @dummy = Dummy.new
@attachment = @dummy.avatar @attachment = @dummy.avatar
end end
Paperclip::Attachment.default_options.keys.each do |key| Paperclip::Attachment.default_options.keys.each do |key|
should "be the new default_options for #{key}" do it "be the new default_options for #{key}" do
assert_equal @new_default_options[key], assert_equal @new_default_options[key],
@attachment.instance_variable_get("@options")[key], @attachment.instance_variable_get("@options")[key],
key key.to_s
end end
end end
end end
...@@ -295,7 +283,7 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -295,7 +283,7 @@ class AttachmentTest < Test::Unit::TestCase
end end
context "An attachment with similarly named interpolations" do context "An attachment with similarly named interpolations" do
setup do before do
rebuild_model :path => ":id.omg/:id-bbq/:idwhat/:id_partition.wtf" rebuild_model :path => ":id.omg/:id-bbq/:idwhat/:id_partition.wtf"
@dummy = Dummy.new @dummy = Dummy.new
@dummy.stubs(:id).returns(1024) @dummy.stubs(:id).returns(1024)
...@@ -303,15 +291,15 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -303,15 +291,15 @@ class AttachmentTest < Test::Unit::TestCase
@dummy.avatar = @file @dummy.avatar = @file
end end
teardown { @file.close } after { @file.close }
should "make sure that they are interpolated correctly" do it "make sure that they are interpolated correctly" do
assert_equal "1024.omg/1024-bbq/1024what/000/001/024.wtf", @dummy.avatar.path assert_equal "1024.omg/1024-bbq/1024what/000/001/024.wtf", @dummy.avatar.path
end end
end end
context "An attachment with :timestamp interpolations" do context "An attachment with :timestamp interpolations" do
setup do before do
@file = StringIO.new("...") @file = StringIO.new("...")
@zone = 'UTC' @zone = 'UTC'
Time.stubs(:zone).returns(@zone) Time.stubs(:zone).returns(@zone)
...@@ -320,47 +308,47 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -320,47 +308,47 @@ class AttachmentTest < Test::Unit::TestCase
end end
context "using default time zone" do context "using default time zone" do
setup do before do
rebuild_model :path => ":timestamp", :use_default_time_zone => true rebuild_model :path => ":timestamp", :use_default_time_zone => true
@dummy = Dummy.new @dummy = Dummy.new
@dummy.avatar = @file @dummy.avatar = @file
end end
should "return a time in the default zone" do it "return a time in the default zone" do
assert_equal @dummy.avatar_updated_at.in_time_zone(@zone_default).to_s, @dummy.avatar.path assert_equal @dummy.avatar_updated_at.in_time_zone(@zone_default).to_s, @dummy.avatar.path
end end
end end
context "using per-thread time zone" do context "using per-thread time zone" do
setup do before do
rebuild_model :path => ":timestamp", :use_default_time_zone => false rebuild_model :path => ":timestamp", :use_default_time_zone => false
@dummy = Dummy.new @dummy = Dummy.new
@dummy.avatar = @file @dummy.avatar = @file
end end
should "return a time in the per-thread zone" do it "return a time in the per-thread zone" do
assert_equal @dummy.avatar_updated_at.in_time_zone(@zone).to_s, @dummy.avatar.path assert_equal @dummy.avatar_updated_at.in_time_zone(@zone).to_s, @dummy.avatar.path
end end
end end
end end
context "An attachment with :hash interpolations" do context "An attachment with :hash interpolations" do
setup do before do
@file = StringIO.new("...\n") @file = StringIO.new("...\n")
end end
should "raise if no secret is provided" do it "raise if no secret is provided" do
rebuild_model :path => ":hash" rebuild_model :path => ":hash"
@attachment = Dummy.new.avatar @attachment = Dummy.new.avatar
@attachment.assign @file @attachment.assign @file
assert_raise ArgumentError do assert_raises ArgumentError do
@attachment.path @attachment.path
end end
end end
context "when secret is set" do context "when secret is set" do
setup do before do
rebuild_model :path => ":hash", rebuild_model :path => ":hash",
:hash_secret => "w00t", :hash_secret => "w00t",
:hash_data => ":class/:attachment/:style/:filename" :hash_data => ":class/:attachment/:style/:filename"
...@@ -368,14 +356,14 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -368,14 +356,14 @@ class AttachmentTest < Test::Unit::TestCase
@attachment.assign @file @attachment.assign @file
end end
should "result in the correct interpolation" do it "result in the correct interpolation" do
assert_equal "dummies/avatars/original/data.txt", assert_equal "dummies/avatars/original/data.txt",
@attachment.send(:interpolate, @attachment.options[:hash_data]) @attachment.send(:interpolate, @attachment.options[:hash_data])
assert_equal "dummies/avatars/thumb/data.txt", assert_equal "dummies/avatars/thumb/data.txt",
@attachment.send(:interpolate, @attachment.options[:hash_data], :thumb) @attachment.send(:interpolate, @attachment.options[:hash_data], :thumb)
end end
should "result in a correct hash" do it "result in a correct hash" do
assert_equal "e1079a5c34ddbd197ebd0280d07952d98a57fb30", @attachment.path assert_equal "e1079a5c34ddbd197ebd0280d07952d98a57fb30", @attachment.path
assert_equal "d740189bd3e49ef226fab84c8d45f7ae4126d043", @attachment.path(:thumb) assert_equal "d740189bd3e49ef226fab84c8d45f7ae4126d043", @attachment.path(:thumb)
end end
...@@ -383,7 +371,7 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -383,7 +371,7 @@ class AttachmentTest < Test::Unit::TestCase
end end
context "An attachment with a :rails_env interpolation" do context "An attachment with a :rails_env interpolation" do
setup do before do
@rails_env = "blah" @rails_env = "blah"
@id = 1024 @id = 1024
rebuild_model :path => ":rails_env/:id.png" rebuild_model :path => ":rails_env/:id.png"
...@@ -394,13 +382,13 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -394,13 +382,13 @@ class AttachmentTest < Test::Unit::TestCase
Rails.stubs(:env).returns(@rails_env) Rails.stubs(:env).returns(@rails_env)
end end
should "return the proper path" do it "return the proper path" do
assert_equal "#{@rails_env}/#{@id}.png", @dummy.avatar.path assert_equal "#{@rails_env}/#{@id}.png", @dummy.avatar.path
end end
end end
context "An attachment with a default style and an extension interpolation" do context "An attachment with a default style and an extension interpolation" do
setup do before do
rebuild_model :path => ":basename.:extension", rebuild_model :path => ":basename.:extension",
:styles => { :default => ["100x100", :jpg] }, :styles => { :default => ["100x100", :jpg] },
:default_style => :default :default_style => :default
...@@ -408,14 +396,14 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -408,14 +396,14 @@ class AttachmentTest < Test::Unit::TestCase
@file = File.open(fixture_file("5k.png")) @file = File.open(fixture_file("5k.png"))
@file.stubs(:original_filename).returns("file.png") @file.stubs(:original_filename).returns("file.png")
end end
should "return the right extension for the path" do it "return the right extension for the path" do
@attachment.assign(@file) @attachment.assign(@file)
assert_equal "file.jpg", @attachment.path assert_equal "file.jpg", @attachment.path
end end
end end
context "An attachment with :convert_options" do context "An attachment with :convert_options" do
setup do before do
rebuild_model :styles => { rebuild_model :styles => {
:thumb => "100x100", :thumb => "100x100",
:large => "400x400" :large => "400x400"
...@@ -428,17 +416,17 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -428,17 +416,17 @@ class AttachmentTest < Test::Unit::TestCase
@dummy.avatar @dummy.avatar
end end
should "report the correct options when sent #extra_options_for(:thumb)" do it "report the correct options when sent #extra_options_for(:thumb)" do
assert_equal "-thumbnailize -do_stuff", @dummy.avatar.send(:extra_options_for, :thumb), @dummy.avatar.convert_options.inspect assert_equal "-thumbnailize -do_stuff", @dummy.avatar.send(:extra_options_for, :thumb), @dummy.avatar.convert_options.inspect
end end
should "report the correct options when sent #extra_options_for(:large)" do it "report the correct options when sent #extra_options_for(:large)" do
assert_equal "-do_stuff", @dummy.avatar.send(:extra_options_for, :large) assert_equal "-do_stuff", @dummy.avatar.send(:extra_options_for, :large)
end end
end end
context "An attachment with :source_file_options" do context "An attachment with :source_file_options" do
setup do before do
rebuild_model :styles => { rebuild_model :styles => {
:thumb => "100x100", :thumb => "100x100",
:large => "400x400" :large => "400x400"
...@@ -451,17 +439,17 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -451,17 +439,17 @@ class AttachmentTest < Test::Unit::TestCase
@dummy.avatar @dummy.avatar
end end
should "report the correct options when sent #extra_source_file_options_for(:thumb)" do it "report the correct options when sent #extra_source_file_options_for(:thumb)" do
assert_equal "-depth 8 -density 400", @dummy.avatar.send(:extra_source_file_options_for, :thumb), @dummy.avatar.source_file_options.inspect assert_equal "-depth 8 -density 400", @dummy.avatar.send(:extra_source_file_options_for, :thumb), @dummy.avatar.source_file_options.inspect
end end
should "report the correct options when sent #extra_source_file_options_for(:large)" do it "report the correct options when sent #extra_source_file_options_for(:large)" do
assert_equal "-density 400", @dummy.avatar.send(:extra_source_file_options_for, :large) assert_equal "-density 400", @dummy.avatar.send(:extra_source_file_options_for, :large)
end end
end end
context "An attachment with :only_process" do context "An attachment with :only_process" do
setup do before do
rebuild_model :styles => { rebuild_model :styles => {
:thumb => "100x100", :thumb => "100x100",
:large => "400x400" :large => "400x400"
...@@ -471,7 +459,7 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -471,7 +459,7 @@ class AttachmentTest < Test::Unit::TestCase
@attachment = Dummy.new.avatar @attachment = Dummy.new.avatar
end end
should "only process the provided style" do it "only process the provided style" do
@attachment.expects(:post_process).with(:thumb) @attachment.expects(:post_process).with(:thumb)
@attachment.expects(:post_process).with(:large).never @attachment.expects(:post_process).with(:large).never
@attachment.assign(@file) @attachment.assign(@file)
...@@ -479,7 +467,7 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -479,7 +467,7 @@ class AttachmentTest < Test::Unit::TestCase
end end
context "An attachment with :only_process that is a proc" do context "An attachment with :only_process that is a proc" do
setup do before do
rebuild_model :styles => { rebuild_model :styles => {
:thumb => "100x100", :thumb => "100x100",
:large => "400x400" :large => "400x400"
...@@ -490,7 +478,7 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -490,7 +478,7 @@ class AttachmentTest < Test::Unit::TestCase
@attachment = Dummy.new.avatar @attachment = Dummy.new.avatar
end end
should "only process the provided style" do it "only process the provided style" do
@attachment.expects(:post_process).with(:thumb) @attachment.expects(:post_process).with(:thumb)
@attachment.expects(:post_process).with(:large).never @attachment.expects(:post_process).with(:large).never
@attachment.assign(@file) @attachment.assign(@file)
...@@ -498,7 +486,7 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -498,7 +486,7 @@ class AttachmentTest < Test::Unit::TestCase
end end
context "An attachment with :convert_options that is a proc" do context "An attachment with :convert_options that is a proc" do
setup do before do
rebuild_model :styles => { rebuild_model :styles => {
:thumb => "100x100", :thumb => "100x100",
:large => "400x400" :large => "400x400"
...@@ -515,17 +503,17 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -515,17 +503,17 @@ class AttachmentTest < Test::Unit::TestCase
@dummy.avatar @dummy.avatar
end end
should "report the correct options when sent #extra_options_for(:thumb)" do it "report the correct options when sent #extra_options_for(:thumb)" do
assert_equal "-thumb -all", @dummy.avatar.send(:extra_options_for, :thumb), @dummy.avatar.convert_options.inspect assert_equal "-thumb -all", @dummy.avatar.send(:extra_options_for, :thumb), @dummy.avatar.convert_options.inspect
end end
should "report the correct options when sent #extra_options_for(:large)" do it "report the correct options when sent #extra_options_for(:large)" do
assert_equal "-all", @dummy.avatar.send(:extra_options_for, :large) assert_equal "-all", @dummy.avatar.send(:extra_options_for, :large)
end end
end end
context "An attachment with :path that is a proc" do context "An attachment with :path that is a proc" do
setup do before do
rebuild_model :path => lambda{ |attachment| "path/#{attachment.instance.other}.:extension" } rebuild_model :path => lambda{ |attachment| "path/#{attachment.instance.other}.:extension" }
@file = File.new(fixture_file("5k.png"), 'rb') @file = File.new(fixture_file("5k.png"), 'rb')
...@@ -535,34 +523,34 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -535,34 +523,34 @@ class AttachmentTest < Test::Unit::TestCase
@dummyB.avatar = @file @dummyB.avatar = @file
end end
teardown { @file.close } after { @file.close }
should "return correct path" do it "return correct path" do
assert_equal "path/a.png", @dummyA.avatar.path assert_equal "path/a.png", @dummyA.avatar.path
assert_equal "path/b.png", @dummyB.avatar.path assert_equal "path/b.png", @dummyB.avatar.path
end end
end end
context "An attachment with :styles that is a proc" do context "An attachment with :styles that is a proc" do
setup do before do
rebuild_model :styles => lambda{ |attachment| {:thumb => "50x50#", :large => "400x400"} } rebuild_model :styles => lambda{ |attachment| {:thumb => "50x50#", :large => "400x400"} }
@attachment = Dummy.new.avatar @attachment = Dummy.new.avatar
end end
should "have the correct geometry" do it "have the correct geometry" do
assert_equal "50x50#", @attachment.styles[:thumb][:geometry] assert_equal "50x50#", @attachment.styles[:thumb][:geometry]
end end
end end
context "An attachment with conditional :styles that is a proc" do context "An attachment with conditional :styles that is a proc" do
setup do before do
rebuild_model :styles => lambda{ |attachment| attachment.instance.other == 'a' ? {:thumb => "50x50#"} : {:large => "400x400"} } rebuild_model :styles => lambda{ |attachment| attachment.instance.other == 'a' ? {:thumb => "50x50#"} : {:large => "400x400"} }
@dummy = Dummy.new(:other => 'a') @dummy = Dummy.new(:other => 'a')
end end
should "have the correct styles for the assigned instance values" do it "have the correct styles for the assigned instance values" do
assert_equal "50x50#", @dummy.avatar.styles[:thumb][:geometry] assert_equal "50x50#", @dummy.avatar.styles[:thumb][:geometry]
assert_nil @dummy.avatar.styles[:large] assert_nil @dummy.avatar.styles[:large]
...@@ -580,18 +568,18 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -580,18 +568,18 @@ class AttachmentTest < Test::Unit::TestCase
] ]
geometry_specs.each do |geometry_spec| geometry_specs.each do |geometry_spec|
context "An attachment geometry like #{geometry_spec}" do context "An attachment geometry like #{geometry_spec}" do
setup do before do
rebuild_model :styles => { :normal => geometry_spec } rebuild_model :styles => { :normal => geometry_spec }
@attachment = Dummy.new.avatar @attachment = Dummy.new.avatar
end end
context "when assigned" do context "when assigned" do
setup do before do
@file = StringIO.new(".") @file = StringIO.new(".")
@attachment.assign(@file) @attachment.assign(@file)
end end
should "have the correct geometry" do it "have the correct geometry" do
assert_equal "50x50#", @attachment.styles[:normal][:geometry] assert_equal "50x50#", @attachment.styles[:normal][:geometry]
end end
end end
...@@ -599,7 +587,7 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -599,7 +587,7 @@ class AttachmentTest < Test::Unit::TestCase
end end
context "An attachment with both 'normal' and hash-style styles" do context "An attachment with both 'normal' and hash-style styles" do
setup do before do
rebuild_model :styles => { rebuild_model :styles => {
:normal => ["50x50#", :png], :normal => ["50x50#", :png],
:hash => { :geometry => "50x50#", :format => :png } :hash => { :geometry => "50x50#", :format => :png }
...@@ -609,14 +597,14 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -609,14 +597,14 @@ class AttachmentTest < Test::Unit::TestCase
end end
[:processors, :whiny, :convert_options, :geometry, :format].each do |field| [:processors, :whiny, :convert_options, :geometry, :format].each do |field|
should "have the same #{field} field" do it "have the same #{field} field" do
assert_equal @attachment.styles[:normal][field], @attachment.styles[:hash][field] assert_equal @attachment.styles[:normal][field], @attachment.styles[:hash][field]
end end
end end
end end
context "An attachment with :processors that is a proc" do context "An attachment with :processors that is a proc" do
setup do before do
class Paperclip::Test < Paperclip::Processor; end class Paperclip::Test < Paperclip::Processor; end
@file = StringIO.new("...") @file = StringIO.new("...")
Paperclip::Test.stubs(:make).returns(@file) Paperclip::Test.stubs(:make).returns(@file)
...@@ -626,18 +614,18 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -626,18 +614,18 @@ class AttachmentTest < Test::Unit::TestCase
end end
context "when assigned" do context "when assigned" do
setup do before do
@attachment.assign(StringIO.new(".")) @attachment.assign(StringIO.new("."))
end end
should "have the correct processors" do it "have the correct processors" do
assert_equal [ :test ], @attachment.styles[:normal][:processors] assert_equal [ :test ], @attachment.styles[:normal][:processors]
end end
end end
end end
context "An attachment with erroring processor" do context "An attachment with erroring processor" do
setup do before do
rebuild_model :processor => [:thumbnail], :styles => { :small => '' }, :whiny_thumbnails => true rebuild_model :processor => [:thumbnail], :styles => { :small => '' }, :whiny_thumbnails => true
@dummy = Dummy.new @dummy = Dummy.new
Paperclip::Thumbnail.expects(:make).raises(Paperclip::Error, "cannot be processed.") Paperclip::Thumbnail.expects(:make).raises(Paperclip::Error, "cannot be processed.")
...@@ -646,14 +634,14 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -646,14 +634,14 @@ class AttachmentTest < Test::Unit::TestCase
@dummy.avatar = @file @dummy.avatar = @file
end end
should "correctly forward processing error message to the instance" do it "correctly forward processing error message to the instance" do
@dummy.valid? @dummy.valid?
assert_contains @dummy.errors.full_messages, "Avatar cannot be processed." assert_contains @dummy.errors.full_messages, "Avatar cannot be processed."
end end
end end
context "An attachment with multiple processors" do context "An attachment with multiple processors" do
setup do before do
class Paperclip::Test < Paperclip::Processor; end class Paperclip::Test < Paperclip::Processor; end
@style_params = { :once => {:one => 1, :two => 2} } @style_params = { :once => {:one => 1, :two => 2} }
rebuild_model :processors => [:thumbnail, :test], :styles => @style_params rebuild_model :processors => [:thumbnail, :test], :styles => @style_params
...@@ -665,36 +653,47 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -665,36 +653,47 @@ class AttachmentTest < Test::Unit::TestCase
end end
context "when assigned" do context "when assigned" do
setup { @dummy.avatar = @file } it "call #make on all specified processors" do
Paperclip::Thumbnail.stubs(:make).with(any_parameters).returns(@file)
Paperclip::Test.stubs(:make).with(any_parameters).returns(@file)
before_should "call #make on all specified processors" do @dummy.avatar = @file
Paperclip::Thumbnail.expects(:make).with(any_parameters).returns(@file)
Paperclip::Test.expects(:make).with(any_parameters).returns(@file) expect(Paperclip::Thumbnail).to have_received(:make)
expect(Paperclip::Test).to have_received(:make)
end end
before_should "call #make with the right parameters passed as second argument" do it "call #make with the right parameters passed as second argument" do
expected_params = @style_params[:once].merge({ expected_params = @style_params[:once].merge({
:processors => [:thumbnail, :test], :processors => [:thumbnail, :test],
:whiny => true, :whiny => true,
:convert_options => "", :convert_options => "",
:source_file_options => "" :source_file_options => ""
}) })
Paperclip::Thumbnail.expects(:make).with(anything, expected_params, anything).returns(@file) Paperclip::Thumbnail.stubs(:make).returns(@file)
@dummy.avatar = @file
expect(Paperclip::Thumbnail).to have_received(:make).with(anything, expected_params, anything)
end end
before_should "call #make with attachment passed as third argument" do it "call #make with attachment passed as third argument" do
Paperclip::Test.expects(:make).with(anything, anything, @dummy.avatar).returns(@file) Paperclip::Test.expects(:make).returns(@file)
@dummy.avatar = @file
expect(Paperclip::Test).to have_received(:make).with(anything, anything, @dummy.avatar)
end end
end end
end end
should "include the filesystem module when loading the filesystem storage" do it "include the filesystem module when loading the filesystem storage" do
rebuild_model :storage => :filesystem rebuild_model :storage => :filesystem
@dummy = Dummy.new @dummy = Dummy.new
assert @dummy.avatar.is_a?(Paperclip::Storage::Filesystem) assert @dummy.avatar.is_a?(Paperclip::Storage::Filesystem)
end end
should "include the filesystem module even if capitalization is wrong" do it "include the filesystem module even if capitalization is wrong" do
rebuild_model :storage => :FileSystem rebuild_model :storage => :FileSystem
@dummy = Dummy.new @dummy = Dummy.new
assert @dummy.avatar.is_a?(Paperclip::Storage::Filesystem) assert @dummy.avatar.is_a?(Paperclip::Storage::Filesystem)
...@@ -704,16 +703,15 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -704,16 +703,15 @@ class AttachmentTest < Test::Unit::TestCase
assert @dummy.avatar.is_a?(Paperclip::Storage::Filesystem) assert @dummy.avatar.is_a?(Paperclip::Storage::Filesystem)
end end
should "convert underscored storage name to camelcase" do it "convert underscored storage name to camelcase" do
rebuild_model :storage => :not_here rebuild_model :storage => :not_here
@dummy = Dummy.new @dummy = Dummy.new
exception = assert_raises(Paperclip::Errors::StorageMethodNotFound) do exception = assert_raises(Paperclip::Errors::StorageMethodNotFound, /NotHere/) do
@dummy.avatar @dummy.avatar
end end
assert exception.message.include?("NotHere")
end end
should "raise an error if you try to include a storage module that doesn't exist" do it "raise an error if you try to include a storage module that doesn't exist" do
rebuild_model :storage => :not_here rebuild_model :storage => :not_here
@dummy = Dummy.new @dummy = Dummy.new
assert_raises(Paperclip::Errors::StorageMethodNotFound) do assert_raises(Paperclip::Errors::StorageMethodNotFound) do
...@@ -722,29 +720,29 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -722,29 +720,29 @@ class AttachmentTest < Test::Unit::TestCase
end end
context "An attachment with styles but no processors defined" do context "An attachment with styles but no processors defined" do
setup do before do
rebuild_model :processors => [], :styles => {:something => '1'} rebuild_model :processors => [], :styles => {:something => '1'}
@dummy = Dummy.new @dummy = Dummy.new
@file = StringIO.new("...") @file = StringIO.new("...")
end end
should "raise when assigned to" do it "raise when assigned to" do
assert_raises(RuntimeError){ @dummy.avatar = @file } assert_raises(RuntimeError){ @dummy.avatar = @file }
end end
end end
context "An attachment without styles and with no processors defined" do context "An attachment without styles and with no processors defined" do
setup do before do
rebuild_model :processors => [], :styles => {} rebuild_model :processors => [], :styles => {}
@dummy = Dummy.new @dummy = Dummy.new
@file = StringIO.new("...") @file = StringIO.new("...")
end end
should "not raise when assigned to" do it "not raise when assigned to" do
@dummy.avatar = @file @dummy.avatar = @file
end end
end end
context "Assigning an attachment with post_process hooks" do context "Assigning an attachment with post_process hooks" do
setup do before do
rebuild_class :styles => { :something => "100x100#" } rebuild_class :styles => { :something => "100x100#" }
Dummy.class_eval do Dummy.class_eval do
before_avatar_post_process :do_before_avatar before_avatar_post_process :do_before_avatar
...@@ -763,7 +761,7 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -763,7 +761,7 @@ class AttachmentTest < Test::Unit::TestCase
@attachment = @dummy.avatar @attachment = @dummy.avatar
end end
should "call the defined callbacks when assigned" do it "call the defined callbacks when assigned" do
@dummy.expects(:do_before_avatar).with() @dummy.expects(:do_before_avatar).with()
@dummy.expects(:do_after_avatar).with() @dummy.expects(:do_after_avatar).with()
@dummy.expects(:do_before_all).with() @dummy.expects(:do_before_all).with()
...@@ -772,7 +770,7 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -772,7 +770,7 @@ class AttachmentTest < Test::Unit::TestCase
@dummy.avatar = @file @dummy.avatar = @file
end end
should "not cancel the processing if a before_post_process returns nil" do it "not cancel the processing if a before_post_process returns nil" do
@dummy.expects(:do_before_avatar).with().returns(nil) @dummy.expects(:do_before_avatar).with().returns(nil)
@dummy.expects(:do_after_avatar).with() @dummy.expects(:do_after_avatar).with()
@dummy.expects(:do_before_all).with().returns(nil) @dummy.expects(:do_before_all).with().returns(nil)
...@@ -781,7 +779,7 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -781,7 +779,7 @@ class AttachmentTest < Test::Unit::TestCase
@dummy.avatar = @file @dummy.avatar = @file
end end
should "cancel the processing if a before_post_process returns false" do it "cancel the processing if a before_post_process returns false" do
@dummy.expects(:do_before_avatar).never @dummy.expects(:do_before_avatar).never
@dummy.expects(:do_after_avatar).never @dummy.expects(:do_after_avatar).never
@dummy.expects(:do_before_all).with().returns(false) @dummy.expects(:do_before_all).with().returns(false)
...@@ -790,7 +788,7 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -790,7 +788,7 @@ class AttachmentTest < Test::Unit::TestCase
@dummy.avatar = @file @dummy.avatar = @file
end end
should "cancel the processing if a before_avatar_post_process returns false" do it "cancel the processing if a before_avatar_post_process returns false" do
@dummy.expects(:do_before_avatar).with().returns(false) @dummy.expects(:do_before_avatar).with().returns(false)
@dummy.expects(:do_after_avatar) @dummy.expects(:do_after_avatar)
@dummy.expects(:do_before_all).with().returns(true) @dummy.expects(:do_before_all).with().returns(true)
...@@ -801,37 +799,37 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -801,37 +799,37 @@ class AttachmentTest < Test::Unit::TestCase
end end
context "Assigning an attachment" do context "Assigning an attachment" do
setup do before do
rebuild_model :styles => { :something => "100x100#" } rebuild_model :styles => { :something => "100x100#" }
@file = File.new(fixture_file("5k.png"), "rb") @file = File.new(fixture_file("5k.png"), "rb")
@dummy = Dummy.new @dummy = Dummy.new
@dummy.avatar = @file @dummy.avatar = @file
end end
should "strip whitespace from original_filename field" do it "strip whitespace from original_filename field" do
assert_equal "5k.png", @dummy.avatar.original_filename assert_equal "5k.png", @dummy.avatar.original_filename
end end
should "strip whitespace from content_type field" do it "strip whitespace from content_type field" do
assert_equal "image/png", @dummy.avatar.instance.avatar_content_type assert_equal "image/png", @dummy.avatar.instance.avatar_content_type
end end
end end
context "Assigning an attachment" do context "Assigning an attachment" do
setup do before do
rebuild_model :styles => { :something => "100x100#" } rebuild_model :styles => { :something => "100x100#" }
@file = File.new(fixture_file("5k.png"), "rb") @file = File.new(fixture_file("5k.png"), "rb")
@dummy = Dummy.new @dummy = Dummy.new
@dummy.avatar = @file @dummy.avatar = @file
end end
should "make sure the content_type is a string" do it "make sure the content_type is a string" do
assert_equal "image/png", @dummy.avatar.instance.avatar_content_type assert_equal "image/png", @dummy.avatar.instance.avatar_content_type
end end
end end
context "Attachment with strange letters" do context "Attachment with strange letters" do
setup do before do
rebuild_model rebuild_model
@file = File.new(fixture_file("5k.png"), "rb") @file = File.new(fixture_file("5k.png"), "rb")
@file.stubs(:original_filename).returns("sheep_say_bæ.png") @file.stubs(:original_filename).returns("sheep_say_bæ.png")
...@@ -839,18 +837,18 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -839,18 +837,18 @@ class AttachmentTest < Test::Unit::TestCase
@dummy.avatar = @file @dummy.avatar = @file
end end
should "not remove strange letters" do it "not remove strange letters" do
assert_equal "sheep_say_bæ.png", @dummy.avatar.original_filename assert_equal "sheep_say_bæ.png", @dummy.avatar.original_filename
end end
end end
context "Attachment with reserved filename" do context "Attachment with reserved filename" do
setup do before do
rebuild_model rebuild_model
@file = Tempfile.new(["filename","png"]) @file = Tempfile.new(["filename","png"])
end end
teardown do after do
@file.unlink @file.unlink
end end
...@@ -859,37 +857,37 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -859,37 +857,37 @@ class AttachmentTest < Test::Unit::TestCase
context "with character #{character}" do context "with character #{character}" do
context "at beginning of filename" do context "at beginning of filename" do
setup do before do
@file.stubs(:original_filename).returns("#{character}filename.png") @file.stubs(:original_filename).returns("#{character}filename.png")
@dummy = Dummy.new @dummy = Dummy.new
@dummy.avatar = @file @dummy.avatar = @file
end end
should "convert special character into underscore" do it "convert special character into underscore" do
assert_equal "_filename.png", @dummy.avatar.original_filename assert_equal "_filename.png", @dummy.avatar.original_filename
end end
end end
context "at end of filename" do context "at end of filename" do
setup do before do
@file.stubs(:original_filename).returns("filename.png#{character}") @file.stubs(:original_filename).returns("filename.png#{character}")
@dummy = Dummy.new @dummy = Dummy.new
@dummy.avatar = @file @dummy.avatar = @file
end end
should "convert special character into underscore" do it "convert special character into underscore" do
assert_equal "filename.png_", @dummy.avatar.original_filename assert_equal "filename.png_", @dummy.avatar.original_filename
end end
end end
context "in the middle of filename" do context "in the middle of filename" do
setup do before do
@file.stubs(:original_filename).returns("file#{character}name.png") @file.stubs(:original_filename).returns("file#{character}name.png")
@dummy = Dummy.new @dummy = Dummy.new
@dummy.avatar = @file @dummy.avatar = @file
end end
should "convert special character into underscore" do it "convert special character into underscore" do
assert_equal "file_name.png", @dummy.avatar.original_filename assert_equal "file_name.png", @dummy.avatar.original_filename
end end
end end
...@@ -899,16 +897,16 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -899,16 +897,16 @@ class AttachmentTest < Test::Unit::TestCase
end end
context "with specified regexp replacement" do context "with specified regexp replacement" do
setup do before do
@old_defaults = Paperclip::Attachment.default_options.dup @old_defaults = Paperclip::Attachment.default_options.dup
end end
teardown do after do
Paperclip::Attachment.default_options.merge! @old_defaults Paperclip::Attachment.default_options.merge! @old_defaults
end end
context 'as another regexp' do context 'as another regexp' do
setup do before do
Paperclip::Attachment.default_options.merge! :restricted_characters => /o/ Paperclip::Attachment.default_options.merge! :restricted_characters => /o/
@file.stubs(:original_filename).returns("goood.png") @file.stubs(:original_filename).returns("goood.png")
...@@ -916,13 +914,13 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -916,13 +914,13 @@ class AttachmentTest < Test::Unit::TestCase
@dummy.avatar = @file @dummy.avatar = @file
end end
should "match and convert that character" do it "match and convert that character" do
assert_equal "g___d.png", @dummy.avatar.original_filename assert_equal "g___d.png", @dummy.avatar.original_filename
end end
end end
context 'as nil' do context 'as nil' do
setup do before do
Paperclip::Attachment.default_options.merge! :restricted_characters => nil Paperclip::Attachment.default_options.merge! :restricted_characters => nil
@file.stubs(:original_filename).returns("goood.png") @file.stubs(:original_filename).returns("goood.png")
...@@ -930,22 +928,22 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -930,22 +928,22 @@ class AttachmentTest < Test::Unit::TestCase
@dummy.avatar = @file @dummy.avatar = @file
end end
should "ignore and return the original file name" do it "ignore and return the original file name" do
assert_equal "goood.png", @dummy.avatar.original_filename assert_equal "goood.png", @dummy.avatar.original_filename
end end
end end
end end
context 'with specified cleaner' do context 'with specified cleaner' do
setup do before do
@old_defaults = Paperclip::Attachment.default_options.dup @old_defaults = Paperclip::Attachment.default_options.dup
end end
teardown do after do
Paperclip::Attachment.default_options.merge! @old_defaults Paperclip::Attachment.default_options.merge! @old_defaults
end end
should 'call the given proc and take the result as cleaned filename' do it 'call the given proc and take the result as cleaned filename' do
Paperclip::Attachment.default_options[:filename_cleaner] = lambda do |str| Paperclip::Attachment.default_options[:filename_cleaner] = lambda do |str|
"from_proc_#{str}" "from_proc_#{str}"
end end
...@@ -956,7 +954,7 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -956,7 +954,7 @@ class AttachmentTest < Test::Unit::TestCase
assert_equal "from_proc_goood.png", @dummy.avatar.original_filename assert_equal "from_proc_goood.png", @dummy.avatar.original_filename
end end
should 'call the given object and take the result as the cleaned filename' do it 'call the given object and take the result as the cleaned filename' do
class MyCleaner class MyCleaner
def call(filename) def call(filename)
"foo" "foo"
...@@ -973,7 +971,7 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -973,7 +971,7 @@ class AttachmentTest < Test::Unit::TestCase
end end
context "Attachment with uppercase extension and a default style" do context "Attachment with uppercase extension and a default style" do
setup do before do
@old_defaults = Paperclip::Attachment.default_options.dup @old_defaults = Paperclip::Attachment.default_options.dup
Paperclip::Attachment.default_options.merge!({ Paperclip::Attachment.default_options.merge!({
:path => ":rails_root/:attachment/:class/:style/:id/:basename.:extension" :path => ":rails_root/:attachment/:class/:style/:id/:basename.:extension"
...@@ -995,23 +993,23 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -995,23 +993,23 @@ class AttachmentTest < Test::Unit::TestCase
@attachment.save @attachment.save
end end
teardown do after do
@file.close @file.close
Paperclip::Attachment.default_options.merge!(@old_defaults) Paperclip::Attachment.default_options.merge!(@old_defaults)
end end
should "should have matching to_s and url methods" do it "should have matching to_s and url methods" do
assert_match @attachment.to_s, @attachment.url assert_equal @attachment.to_s, @attachment.url
assert_match @attachment.to_s(:small), @attachment.url(:small) assert_equal @attachment.to_s(:small), @attachment.url(:small)
end end
should "have matching expiring_url and url methods when using the filesystem storage" do it "have matching expiring_url and url methods when using the filesystem storage" do
assert_match @attachment.expiring_url, @attachment.url assert_equal @attachment.expiring_url, @attachment.url
end end
end end
context "An attachment" do context "An attachment" do
setup do before do
@old_defaults = Paperclip::Attachment.default_options.dup @old_defaults = Paperclip::Attachment.default_options.dup
Paperclip::Attachment.default_options.merge!({ Paperclip::Attachment.default_options.merge!({
:path => ":rails_root/:attachment/:class/:style/:id/:basename.:extension" :path => ":rails_root/:attachment/:class/:style/:id/:basename.:extension"
...@@ -1025,39 +1023,39 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -1025,39 +1023,39 @@ class AttachmentTest < Test::Unit::TestCase
@file = File.new(fixture_file("5k.png"), 'rb') @file = File.new(fixture_file("5k.png"), 'rb')
end end
teardown do after do
@file.close @file.close
Paperclip::Attachment.default_options.merge!(@old_defaults) Paperclip::Attachment.default_options.merge!(@old_defaults)
end end
should "raise if there are not the correct columns when you try to assign" do it "raise if there are not the correct columns when you try to assign" do
@other_attachment = Paperclip::Attachment.new(:not_here, @instance) @other_attachment = Paperclip::Attachment.new(:not_here, @instance)
assert_raises(Paperclip::Error) do assert_raises(Paperclip::Error) do
@other_attachment.assign(@file) @other_attachment.assign(@file)
end end
end end
should 'clear out the previous assignment when assigned nil' do it 'clear out the previous assignment when assigned nil' do
@attachment.assign(@file) @attachment.assign(@file)
@attachment.queued_for_write[:original] @attachment.queued_for_write[:original]
@attachment.assign(nil) @attachment.assign(nil)
assert_nil @attachment.queued_for_write[:original] assert_nil @attachment.queued_for_write[:original]
end end
should 'not do anything when it is assigned an empty string' do it 'not do anything when it is assigned an empty string' do
@attachment.assign(@file) @attachment.assign(@file)
original_file = @attachment.queued_for_write[:original] original_file = @attachment.queued_for_write[:original]
@attachment.assign("") @attachment.assign("")
assert_equal original_file, @attachment.queued_for_write[:original] assert_equal original_file, @attachment.queued_for_write[:original]
end end
should "return nil as path when no file assigned" do it "return nil as path when no file assigned" do
assert_equal nil, @attachment.path assert_equal nil, @attachment.path
assert_equal nil, @attachment.path(:blah) assert_equal nil, @attachment.path(:blah)
end end
context "with a file assigned but not saved yet" do context "with a file assigned but not saved yet" do
should "clear out any attached files" do it "clear out any attached files" do
@attachment.assign(@file) @attachment.assign(@file)
assert !@attachment.queued_for_write.blank? assert !@attachment.queued_for_write.blank?
@attachment.clear @attachment.clear
...@@ -1066,7 +1064,7 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -1066,7 +1064,7 @@ class AttachmentTest < Test::Unit::TestCase
end end
context "with a file assigned in the database" do context "with a file assigned in the database" do
setup do before do
@attachment.stubs(:instance_read).with(:file_name).returns("5k.png") @attachment.stubs(:instance_read).with(:file_name).returns("5k.png")
@attachment.stubs(:instance_read).with(:content_type).returns("image/png") @attachment.stubs(:instance_read).with(:content_type).returns("image/png")
@attachment.stubs(:instance_read).with(:file_size).returns(12345) @attachment.stubs(:instance_read).with(:file_size).returns(12345)
...@@ -1076,17 +1074,17 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -1076,17 +1074,17 @@ class AttachmentTest < Test::Unit::TestCase
@attachment.stubs(:instance_read).with(:updated_at).returns(dtnow) @attachment.stubs(:instance_read).with(:updated_at).returns(dtnow)
end end
should "return the proper path when filename has a single .'s" do it "return the proper path when filename has a single .'s" do
assert_equal File.expand_path("tmp/avatars/dummies/original/#{@instance.id}/5k.png"), File.expand_path(@attachment.path) assert_equal File.expand_path("tmp/avatars/dummies/original/#{@instance.id}/5k.png"), File.expand_path(@attachment.path)
end end
should "return the proper path when filename has multiple .'s" do it "return the proper path when filename has multiple .'s" do
@attachment.stubs(:instance_read).with(:file_name).returns("5k.old.png") @attachment.stubs(:instance_read).with(:file_name).returns("5k.old.png")
assert_equal File.expand_path("tmp/avatars/dummies/original/#{@instance.id}/5k.old.png"), File.expand_path(@attachment.path) assert_equal File.expand_path("tmp/avatars/dummies/original/#{@instance.id}/5k.old.png"), File.expand_path(@attachment.path)
end end
context "when expecting three styles" do context "when expecting three styles" do
setup do before do
rebuild_class :styles => { rebuild_class :styles => {
:large => ["400x400", :png], :large => ["400x400", :png],
:medium => ["100x100", :gif], :medium => ["100x100", :gif],
...@@ -1099,28 +1097,28 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -1099,28 +1097,28 @@ class AttachmentTest < Test::Unit::TestCase
end end
context "and assigned a file" do context "and assigned a file" do
setup do before do
now = Time.now now = Time.now
Time.stubs(:now).returns(now) Time.stubs(:now).returns(now)
@attachment.assign(@file) @attachment.assign(@file)
end end
should "be dirty" do it "be dirty" do
assert @attachment.dirty? assert @attachment.dirty?
end end
context "and saved" do context "and saved" do
setup do before do
@attachment.save @attachment.save
end end
should "commit the files to disk" do it "commit the files to disk" do
[:large, :medium, :small].each do |style| [:large, :medium, :small].each do |style|
assert_file_exists(@attachment.path(style)) expect(@attachment.path(style)).to exist
end end
end end
should "save the files as the right formats and sizes" do it "save the files as the right formats and sizes" do
[[:large, 400, 61, "PNG"], [[:large, 400, 61, "PNG"],
[:medium, 100, 15, "GIF"], [:medium, 100, 15, "GIF"],
[:small, 32, 32, "JPEG"]].each do |style| [:small, 32, 32, "JPEG"]].each do |style|
...@@ -1134,13 +1132,13 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -1134,13 +1132,13 @@ class AttachmentTest < Test::Unit::TestCase
end end
context "and trying to delete" do context "and trying to delete" do
setup do before do
@existing_names = @attachment.styles.keys.collect do |style| @existing_names = @attachment.styles.keys.collect do |style|
@attachment.path(style) @attachment.path(style)
end end
end end
should "delete the files after assigning nil" do it "delete the files after assigning nil" do
@attachment.expects(:instance_write).with(:file_name, nil) @attachment.expects(:instance_write).with(:file_name, nil)
@attachment.expects(:instance_write).with(:content_type, nil) @attachment.expects(:instance_write).with(:content_type, nil)
@attachment.expects(:instance_write).with(:file_size, nil) @attachment.expects(:instance_write).with(:file_size, nil)
...@@ -1151,7 +1149,7 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -1151,7 +1149,7 @@ class AttachmentTest < Test::Unit::TestCase
@existing_names.each{|f| assert_file_not_exists(f) } @existing_names.each{|f| assert_file_not_exists(f) }
end end
should "delete the files when you call #clear and #save" do it "delete the files when you call #clear and #save" do
@attachment.expects(:instance_write).with(:file_name, nil) @attachment.expects(:instance_write).with(:file_name, nil)
@attachment.expects(:instance_write).with(:content_type, nil) @attachment.expects(:instance_write).with(:content_type, nil)
@attachment.expects(:instance_write).with(:file_size, nil) @attachment.expects(:instance_write).with(:file_size, nil)
...@@ -1162,7 +1160,7 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -1162,7 +1160,7 @@ class AttachmentTest < Test::Unit::TestCase
@existing_names.each{|f| assert_file_not_exists(f) } @existing_names.each{|f| assert_file_not_exists(f) }
end end
should "delete the files when you call #delete" do it "delete the files when you call #delete" do
@attachment.expects(:instance_write).with(:file_name, nil) @attachment.expects(:instance_write).with(:file_name, nil)
@attachment.expects(:instance_write).with(:content_type, nil) @attachment.expects(:instance_write).with(:content_type, nil)
@attachment.expects(:instance_write).with(:file_size, nil) @attachment.expects(:instance_write).with(:file_size, nil)
...@@ -1173,11 +1171,11 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -1173,11 +1171,11 @@ class AttachmentTest < Test::Unit::TestCase
end end
context "when keeping old files" do context "when keeping old files" do
setup do before do
@attachment.options[:keep_old_files] = true @attachment.options[:keep_old_files] = true
end end
should "keep the files after assigning nil" do it "keep the files after assigning nil" do
@attachment.expects(:instance_write).with(:file_name, nil) @attachment.expects(:instance_write).with(:file_name, nil)
@attachment.expects(:instance_write).with(:content_type, nil) @attachment.expects(:instance_write).with(:content_type, nil)
@attachment.expects(:instance_write).with(:file_size, nil) @attachment.expects(:instance_write).with(:file_size, nil)
...@@ -1188,7 +1186,7 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -1188,7 +1186,7 @@ class AttachmentTest < Test::Unit::TestCase
@existing_names.each{|f| assert_file_exists(f) } @existing_names.each{|f| assert_file_exists(f) }
end end
should "keep the files when you call #clear and #save" do it "keep the files when you call #clear and #save" do
@attachment.expects(:instance_write).with(:file_name, nil) @attachment.expects(:instance_write).with(:file_name, nil)
@attachment.expects(:instance_write).with(:content_type, nil) @attachment.expects(:instance_write).with(:content_type, nil)
@attachment.expects(:instance_write).with(:file_size, nil) @attachment.expects(:instance_write).with(:file_size, nil)
...@@ -1199,7 +1197,7 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -1199,7 +1197,7 @@ class AttachmentTest < Test::Unit::TestCase
@existing_names.each{|f| assert_file_exists(f) } @existing_names.each{|f| assert_file_exists(f) }
end end
should "keep the files when you call #delete" do it "keep the files when you call #delete" do
@attachment.expects(:instance_write).with(:file_name, nil) @attachment.expects(:instance_write).with(:file_name, nil)
@attachment.expects(:instance_write).with(:content_type, nil) @attachment.expects(:instance_write).with(:content_type, nil)
@attachment.expects(:instance_write).with(:file_size, nil) @attachment.expects(:instance_write).with(:file_size, nil)
...@@ -1216,18 +1214,18 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -1216,18 +1214,18 @@ class AttachmentTest < Test::Unit::TestCase
end end
context "when trying a nonexistant storage type" do context "when trying a nonexistant storage type" do
setup do before do
rebuild_model :storage => :not_here rebuild_model :storage => :not_here
end end
should "not be able to find the module" do it "not be able to find the module" do
assert_raise(Paperclip::Errors::StorageMethodNotFound){ Dummy.new.avatar } assert_raises(Paperclip::Errors::StorageMethodNotFound){ Dummy.new.avatar }
end end
end end
end end
context "An attachment with only a avatar_file_name column" do context "An attachment with only a avatar_file_name column" do
setup do before do
ActiveRecord::Base.connection.create_table :dummies, :force => true do |table| ActiveRecord::Base.connection.create_table :dummies, :force => true do |table|
table.column :avatar_file_name, :string table.column :avatar_file_name, :string
end end
...@@ -1236,41 +1234,41 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -1236,41 +1234,41 @@ class AttachmentTest < Test::Unit::TestCase
@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 assigned an attachment" do it "not error when assigned an attachment" do
assert_nothing_raised { @dummy.avatar = @file } assert_nothing_raised { @dummy.avatar = @file }
end end
should "not return the time when sent #avatar_updated_at" do it "not return the time when sent #avatar_updated_at" do
@dummy.avatar = @file @dummy.avatar = @file
assert_nil @dummy.avatar.updated_at assert_nil @dummy.avatar.updated_at
end end
should "return the right value when sent #avatar_file_size" do it "return the right value when sent #avatar_file_size" do
@dummy.avatar = @file @dummy.avatar = @file
assert_equal File.size(@file), @dummy.avatar.size assert_equal File.size(@file), @dummy.avatar.size
end end
context "and avatar_created_at column" do context "and avatar_created_at column" do
setup do before do
ActiveRecord::Base.connection.add_column :dummies, :avatar_created_at, :timestamp ActiveRecord::Base.connection.add_column :dummies, :avatar_created_at, :timestamp
rebuild_class rebuild_class
@dummy = Dummy.new @dummy = Dummy.new
end end
should "not error when assigned an attachment" do it "not error when assigned an attachment" do
assert_nothing_raised { @dummy.avatar = @file } assert_nothing_raised { @dummy.avatar = @file }
end end
should "return the creation time when sent #avatar_created_at" do it "return the creation time when sent #avatar_created_at" do
now = Time.now now = Time.now
Time.stubs(:now).returns(now) Time.stubs(:now).returns(now)
@dummy.avatar = @file @dummy.avatar = @file
assert_equal now.to_i, @dummy.avatar.created_at assert_equal now.to_i, @dummy.avatar.created_at
end end
should "return the creation time when sent #avatar_created_at and the entry has been updated" do it "return the creation time when sent #avatar_created_at and the entry has been updated" do
creation = 2.hours.ago creation = 2.hours.ago
now = Time.now now = Time.now
Time.stubs(:now).returns(creation) Time.stubs(:now).returns(creation)
...@@ -1281,7 +1279,7 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -1281,7 +1279,7 @@ class AttachmentTest < Test::Unit::TestCase
assert_not_equal now.to_i, @dummy.avatar.created_at assert_not_equal now.to_i, @dummy.avatar.created_at
end end
should "set changed? to true on attachment assignment" do it "set changed? to true on attachment assignment" do
@dummy.avatar = @file @dummy.avatar = @file
@dummy.save! @dummy.save!
@dummy.avatar = @file @dummy.avatar = @file
...@@ -1290,17 +1288,17 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -1290,17 +1288,17 @@ class AttachmentTest < Test::Unit::TestCase
end end
context "and avatar_updated_at column" do context "and avatar_updated_at column" do
setup do before do
ActiveRecord::Base.connection.add_column :dummies, :avatar_updated_at, :timestamp ActiveRecord::Base.connection.add_column :dummies, :avatar_updated_at, :timestamp
rebuild_class rebuild_class
@dummy = Dummy.new @dummy = Dummy.new
end end
should "not error when assigned an attachment" do it "not error when assigned an attachment" do
assert_nothing_raised { @dummy.avatar = @file } assert_nothing_raised { @dummy.avatar = @file }
end end
should "return the right value when sent #avatar_updated_at" do it "return the right value when sent #avatar_updated_at" do
now = Time.now now = Time.now
Time.stubs(:now).returns(now) Time.stubs(:now).returns(now)
@dummy.avatar = @file @dummy.avatar = @file
...@@ -1308,45 +1306,45 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -1308,45 +1306,45 @@ class AttachmentTest < Test::Unit::TestCase
end end
end end
should "not calculate fingerprint" do it "not calculate fingerprint" do
@dummy.avatar = @file @dummy.avatar = @file
assert_nil @dummy.avatar.fingerprint assert_nil @dummy.avatar.fingerprint
end end
context "and avatar_content_type column" do context "and avatar_content_type column" do
setup do before do
ActiveRecord::Base.connection.add_column :dummies, :avatar_content_type, :string ActiveRecord::Base.connection.add_column :dummies, :avatar_content_type, :string
rebuild_class rebuild_class
@dummy = Dummy.new @dummy = Dummy.new
end end
should "not error when assigned an attachment" do it "not error when assigned an attachment" do
assert_nothing_raised { @dummy.avatar = @file } assert_nothing_raised { @dummy.avatar = @file }
end end
should "return the right value when sent #avatar_content_type" do it "return the right value when sent #avatar_content_type" do
@dummy.avatar = @file @dummy.avatar = @file
assert_equal "image/png", @dummy.avatar.content_type assert_equal "image/png", @dummy.avatar.content_type
end end
end end
context "and avatar_file_size column" do context "and avatar_file_size column" do
setup do before do
ActiveRecord::Base.connection.add_column :dummies, :avatar_file_size, :integer ActiveRecord::Base.connection.add_column :dummies, :avatar_file_size, :integer
rebuild_class rebuild_class
@dummy = Dummy.new @dummy = Dummy.new
end end
should "not error when assigned an attachment" do it "not error when assigned an attachment" do
assert_nothing_raised { @dummy.avatar = @file } assert_nothing_raised { @dummy.avatar = @file }
end end
should "return the right value when sent #avatar_file_size" do it "return the right value when sent #avatar_file_size" do
@dummy.avatar = @file @dummy.avatar = @file
assert_equal File.size(@file), @dummy.avatar.size assert_equal File.size(@file), @dummy.avatar.size
end end
should "return the right value when saved, reloaded, and sent #avatar_file_size" do it "return the right value when saved, reloaded, and sent #avatar_file_size" do
@dummy.avatar = @file @dummy.avatar = @file
@dummy.save @dummy.save
@dummy = Dummy.find(@dummy.id) @dummy = Dummy.find(@dummy.id)
...@@ -1355,22 +1353,22 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -1355,22 +1353,22 @@ class AttachmentTest < Test::Unit::TestCase
end end
context "and avatar_fingerprint column" do context "and avatar_fingerprint column" do
setup do before do
ActiveRecord::Base.connection.add_column :dummies, :avatar_fingerprint, :string ActiveRecord::Base.connection.add_column :dummies, :avatar_fingerprint, :string
rebuild_class rebuild_class
@dummy = Dummy.new @dummy = Dummy.new
end end
should "not error when assigned an attachment" do it "not error when assigned an attachment" do
assert_nothing_raised { @dummy.avatar = @file } assert_nothing_raised { @dummy.avatar = @file }
end end
should "return the right value when sent #avatar_fingerprint" do it "return the right value when sent #avatar_fingerprint" do
@dummy.avatar = @file @dummy.avatar = @file
assert_equal 'aec488126c3b33c08a10c3fa303acf27', @dummy.avatar_fingerprint assert_equal 'aec488126c3b33c08a10c3fa303acf27', @dummy.avatar_fingerprint
end end
should "return the right value when saved, reloaded, and sent #avatar_fingerprint" do it "return the right value when saved, reloaded, and sent #avatar_fingerprint" do
@dummy.avatar = @file @dummy.avatar = @file
@dummy.save @dummy.save
@dummy = Dummy.find(@dummy.id) @dummy = Dummy.find(@dummy.id)
...@@ -1380,7 +1378,7 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -1380,7 +1378,7 @@ class AttachmentTest < Test::Unit::TestCase
end end
context "an attachment with delete_file option set to false" do context "an attachment with delete_file option set to false" do
setup do before do
rebuild_model :preserve_files => true rebuild_model :preserve_files => true
@dummy = Dummy.new @dummy = Dummy.new
@file = File.new(fixture_file("5k.png"), 'rb') @file = File.new(fixture_file("5k.png"), 'rb')
...@@ -1390,27 +1388,27 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -1390,27 +1388,27 @@ class AttachmentTest < Test::Unit::TestCase
@path = @attachment.path @path = @attachment.path
end end
teardown { @file.close } after { @file.close }
should "not delete the files from storage when attachment is destroyed" do it "not delete the files from storage when attachment is destroyed" do
@attachment.destroy @attachment.destroy
assert_file_exists(@path) assert_file_exists(@path)
end end
should "clear out attachment data when attachment is destroyed" do it "clear out attachment data when attachment is destroyed" do
@attachment.destroy @attachment.destroy
assert !@attachment.exists? assert !@attachment.exists?
assert_nil @dummy.avatar_file_name assert_nil @dummy.avatar_file_name
end end
should "not delete the file when model is destroyed" do it "not delete the file when model is destroyed" do
@dummy.destroy @dummy.destroy
assert_file_exists(@path) assert_file_exists(@path)
end end
end end
context "An attached file" do context "An attached file" do
setup do before do
rebuild_model rebuild_model
@dummy = Dummy.new @dummy = Dummy.new
@file = File.new(fixture_file("5k.png"), 'rb') @file = File.new(fixture_file("5k.png"), 'rb')
...@@ -1420,24 +1418,24 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -1420,24 +1418,24 @@ class AttachmentTest < Test::Unit::TestCase
@path = @attachment.path @path = @attachment.path
end end
teardown { @file.close } after { @file.close }
should "not be deleted when the model fails to destroy" do it "not be deleted when the model fails to destroy" do
@dummy.stubs(:destroy).raises(Exception) @dummy.stubs(:destroy).raises(Exception)
assert_raise Exception do assert_raises Exception do
@dummy.destroy @dummy.destroy
end end
assert_file_exists(@path) assert_file_exists(@path)
end end
should "be deleted when the model is destroyed" do it "be deleted when the model is destroyed" do
@dummy.destroy @dummy.destroy
assert_file_not_exists(@path) assert_file_not_exists(@path)
end end
should "not be deleted when transaction rollbacks after model is destroyed" do it "not be deleted when transaction rollbacks after model is destroyed" do
ActiveRecord::Base.transaction do ActiveRecord::Base.transaction do
@dummy.destroy @dummy.destroy
raise ActiveRecord::Rollback raise ActiveRecord::Rollback
...@@ -1448,3 +1446,4 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -1448,3 +1446,4 @@ class AttachmentTest < Test::Unit::TestCase
end end
end end
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'
class GeometryTest < Test::Unit::TestCase describe Paperclip::Geometry do
context "Paperclip::Geometry" do context "Paperclip::Geometry" do
should "correctly report its given dimensions" do it "correctly report its given dimensions" do
assert @geo = Paperclip::Geometry.new(1024, 768) assert @geo = Paperclip::Geometry.new(1024, 768)
assert_equal 1024, @geo.width assert_equal 1024, @geo.width
assert_equal 768, @geo.height assert_equal 768, @geo.height
end end
should "set height to 0 if height dimension is missing" do it "set height to 0 if height dimension is missing" do
assert @geo = Paperclip::Geometry.new(1024) assert @geo = Paperclip::Geometry.new(1024)
assert_equal 1024, @geo.width assert_equal 1024, @geo.width
assert_equal 0, @geo.height assert_equal 0, @geo.height
end end
should "set width to 0 if width dimension is missing" do it "set width to 0 if width dimension is missing" do
assert @geo = Paperclip::Geometry.new(nil, 768) assert @geo = Paperclip::Geometry.new(nil, 768)
assert_equal 0, @geo.width assert_equal 0, @geo.width
assert_equal 768, @geo.height assert_equal 768, @geo.height
end end
should "be generated from a WxH-formatted string" do it "be generated from a WxH-formatted string" do
assert @geo = Paperclip::Geometry.parse("800x600") assert @geo = Paperclip::Geometry.parse("800x600")
assert_equal 800, @geo.width assert_equal 800, @geo.width
assert_equal 600, @geo.height assert_equal 600, @geo.height
end end
should "be generated from a xH-formatted string" do it "be generated from a xH-formatted string" do
assert @geo = Paperclip::Geometry.parse("x600") assert @geo = Paperclip::Geometry.parse("x600")
assert_equal 0, @geo.width assert_equal 0, @geo.width
assert_equal 600, @geo.height assert_equal 600, @geo.height
end end
should "be generated from a Wx-formatted string" do it "be generated from a Wx-formatted string" do
assert @geo = Paperclip::Geometry.parse("800x") assert @geo = Paperclip::Geometry.parse("800x")
assert_equal 800, @geo.width assert_equal 800, @geo.width
assert_equal 0, @geo.height assert_equal 0, @geo.height
end end
should "be generated from a W-formatted string" do it "be generated from a W-formatted string" do
assert @geo = Paperclip::Geometry.parse("800") assert @geo = Paperclip::Geometry.parse("800")
assert_equal 800, @geo.width assert_equal 800, @geo.width
assert_equal 0, @geo.height assert_equal 0, @geo.height
end end
should "ensure the modifier is nil if not present" do it "ensure the modifier is nil if not present" do
assert @geo = Paperclip::Geometry.parse("123x456") assert @geo = Paperclip::Geometry.parse("123x456")
assert_nil @geo.modifier assert_nil @geo.modifier
end end
should "recognize an EXIF orientation and not rotate with auto_orient if not necessary" do it "recognize an EXIF orientation and not rotate with auto_orient if not necessary" do
geo = Paperclip::Geometry.new(:width => 1024, :height => 768, :orientation => 1) geo = Paperclip::Geometry.new(:width => 1024, :height => 768, :orientation => 1)
assert geo assert geo
assert_equal 1024, geo.width assert_equal 1024, geo.width
...@@ -61,7 +61,7 @@ class GeometryTest < Test::Unit::TestCase ...@@ -61,7 +61,7 @@ class GeometryTest < Test::Unit::TestCase
assert_equal 768, geo.height assert_equal 768, geo.height
end end
should "recognize an EXIF orientation and rotate with auto_orient if necessary" do it "recognize an EXIF orientation and rotate with auto_orient if necessary" do
geo = Paperclip::Geometry.new(:width => 1024, :height => 768, :orientation => 6) geo = Paperclip::Geometry.new(:width => 1024, :height => 768, :orientation => 6)
assert geo assert geo
assert_equal 1024, geo.width assert_equal 1024, geo.width
...@@ -73,7 +73,7 @@ class GeometryTest < Test::Unit::TestCase ...@@ -73,7 +73,7 @@ class GeometryTest < Test::Unit::TestCase
assert_equal 1024, geo.height assert_equal 1024, geo.height
end end
should "treat x and X the same in geometries" do it "treat x and X the same in geometries" do
@lower = Paperclip::Geometry.parse("123x456") @lower = Paperclip::Geometry.parse("123x456")
@upper = Paperclip::Geometry.parse("123X456") @upper = Paperclip::Geometry.parse("123X456")
assert_equal 123, @lower.width assert_equal 123, @lower.width
...@@ -83,48 +83,46 @@ class GeometryTest < Test::Unit::TestCase ...@@ -83,48 +83,46 @@ class GeometryTest < Test::Unit::TestCase
end end
['>', '<', '#', '@', '%', '^', '!', nil].each do |mod| ['>', '<', '#', '@', '%', '^', '!', nil].each do |mod|
should "ensure the modifier #{mod.inspect} is preserved" do it "ensure the modifier #{description} is preserved" do
assert @geo = Paperclip::Geometry.parse("123x456#{mod}") assert @geo = Paperclip::Geometry.parse("123x456#{mod}")
assert_equal mod, @geo.modifier assert_equal mod, @geo.modifier
assert_equal "123x456#{mod}", @geo.to_s assert_equal "123x456#{mod}", @geo.to_s
end end
end
['>', '<', '#', '@', '%', '^', '!', nil].each do |mod| it "ensure the modifier #{description} is preserved with no height" do
should "ensure the modifier #{mod.inspect} is preserved with no height" do
assert @geo = Paperclip::Geometry.parse("123x#{mod}") assert @geo = Paperclip::Geometry.parse("123x#{mod}")
assert_equal mod, @geo.modifier assert_equal mod, @geo.modifier
assert_equal "123#{mod}", @geo.to_s assert_equal "123#{mod}", @geo.to_s
end end
end end
should "make sure the modifier gets passed during transformation_to" do it "make sure the modifier gets passed during transformation_to" do
assert @src = Paperclip::Geometry.parse("123x456") assert @src = Paperclip::Geometry.parse("123x456")
assert @dst = Paperclip::Geometry.parse("123x456>") assert @dst = Paperclip::Geometry.parse("123x456>")
assert_equal ["123x456>", nil], @src.transformation_to(@dst) assert_equal ["123x456>", nil], @src.transformation_to(@dst)
end end
should "generate correct ImageMagick formatting string for W-formatted string" do it "generate correct ImageMagick formatting string for W-formatted string" do
assert @geo = Paperclip::Geometry.parse("800") assert @geo = Paperclip::Geometry.parse("800")
assert_equal "800", @geo.to_s assert_equal "800", @geo.to_s
end end
should "generate correct ImageMagick formatting string for Wx-formatted string" do it "generate correct ImageMagick formatting string for Wx-formatted string" do
assert @geo = Paperclip::Geometry.parse("800x") assert @geo = Paperclip::Geometry.parse("800x")
assert_equal "800", @geo.to_s assert_equal "800", @geo.to_s
end end
should "generate correct ImageMagick formatting string for xH-formatted string" do it "generate correct ImageMagick formatting string for xH-formatted string" do
assert @geo = Paperclip::Geometry.parse("x600") assert @geo = Paperclip::Geometry.parse("x600")
assert_equal "x600", @geo.to_s assert_equal "x600", @geo.to_s
end end
should "generate correct ImageMagick formatting string for WxH-formatted string" do it "generate correct ImageMagick formatting string for WxH-formatted string" do
assert @geo = Paperclip::Geometry.parse("800x600") assert @geo = Paperclip::Geometry.parse("800x600")
assert_equal "800x600", @geo.to_s assert_equal "800x600", @geo.to_s
end end
should "be generated from a file" do it "be generated from a file" do
file = fixture_file("5k.png") file = fixture_file("5k.png")
file = File.new(file, 'rb') file = File.new(file, 'rb')
assert_nothing_raised{ @geo = Paperclip::Geometry.from_file(file) } assert_nothing_raised{ @geo = Paperclip::Geometry.from_file(file) }
...@@ -132,14 +130,14 @@ class GeometryTest < Test::Unit::TestCase ...@@ -132,14 +130,14 @@ class GeometryTest < Test::Unit::TestCase
assert_equal 434, @geo.width assert_equal 434, @geo.width
end end
should "be generated from a file path" do it "be generated from a file path" do
file = fixture_file("5k.png") file = fixture_file("5k.png")
assert_nothing_raised{ @geo = Paperclip::Geometry.from_file(file) } assert_nothing_raised{ @geo = Paperclip::Geometry.from_file(file) }
assert_equal 66, @geo.height assert_equal 66, @geo.height
assert_equal 434, @geo.width assert_equal 434, @geo.width
end end
should 'calculate an EXIF-rotated image dimensions from a path' do it 'calculate an EXIF-rotated image dimensions from a path' do
file = fixture_file("rotated.jpg") file = fixture_file("rotated.jpg")
assert_nothing_raised{ @geo = Paperclip::Geometry.from_file(file) } assert_nothing_raised{ @geo = Paperclip::Geometry.from_file(file) }
@geo.auto_orient @geo.auto_orient
...@@ -147,28 +145,28 @@ class GeometryTest < Test::Unit::TestCase ...@@ -147,28 +145,28 @@ class GeometryTest < Test::Unit::TestCase
assert_equal 200, @geo.width assert_equal 200, @geo.width
end end
should "not generate from a bad file" do it "not generate from a bad file" do
file = "/home/This File Does Not Exist.omg" file = "/home/This File Does Not Exist.omg"
assert_raise(Paperclip::Errors::NotIdentifiedByImageMagickError){ @geo = Paperclip::Geometry.from_file(file) } expect { @geo = Paperclip::Geometry.from_file(file) }.to raise_error(Paperclip::Errors::NotIdentifiedByImageMagickError)
end end
should "not generate from a blank filename" do it "not generate from a blank filename" do
file = "" file = ""
assert_raise(Paperclip::Errors::NotIdentifiedByImageMagickError){ @geo = Paperclip::Geometry.from_file(file) } expect { @geo = Paperclip::Geometry.from_file(file) }.to raise_error(Paperclip::Errors::NotIdentifiedByImageMagickError)
end end
should "not generate from a nil file" do it "not generate from a nil file" do
file = nil file = nil
assert_raise(Paperclip::Errors::NotIdentifiedByImageMagickError){ @geo = Paperclip::Geometry.from_file(file) } expect { @geo = Paperclip::Geometry.from_file(file) }.to raise_error(Paperclip::Errors::NotIdentifiedByImageMagickError)
end end
should "not generate from a file with no path" do it "not generate from a file with no path" do
file = mock("file", :path => "") file = mock("file", :path => "")
file.stubs(:respond_to?).with(:path).returns(true) file.stubs(:respond_to?).with(:path).returns(true)
assert_raise(Paperclip::Errors::NotIdentifiedByImageMagickError){ @geo = Paperclip::Geometry.from_file(file) } expect { @geo = Paperclip::Geometry.from_file(file) }.to raise_error(Paperclip::Errors::NotIdentifiedByImageMagickError)
end end
should "let us know when a command isn't found versus a processing error" do it "let us know when a command isn't found versus a processing error" do
old_path = ENV['PATH'] old_path = ENV['PATH']
begin begin
ENV['PATH'] = '' ENV['PATH'] = ''
...@@ -185,32 +183,32 @@ class GeometryTest < Test::Unit::TestCase ...@@ -185,32 +183,32 @@ class GeometryTest < Test::Unit::TestCase
['horizontal', 1024, 768, false, true, false, 1024, 768, 1.3333], ['horizontal', 1024, 768, false, true, false, 1024, 768, 1.3333],
['square', 100, 100, false, false, true, 100, 100, 1]].each do |args| ['square', 100, 100, false, false, true, 100, 100, 1]].each do |args|
context "performing calculations on a #{args[0]} viewport" do context "performing calculations on a #{args[0]} viewport" do
setup do before do
@geo = Paperclip::Geometry.new(args[1], args[2]) @geo = Paperclip::Geometry.new(args[1], args[2])
end end
should "#{args[3] ? "" : "not"} be vertical" do it "#{args[3] ? "" : "not"} be vertical" do
assert_equal args[3], @geo.vertical? assert_equal args[3], @geo.vertical?
end end
should "#{args[4] ? "" : "not"} be horizontal" do it "#{args[4] ? "" : "not"} be horizontal" do
assert_equal args[4], @geo.horizontal? assert_equal args[4], @geo.horizontal?
end end
should "#{args[5] ? "" : "not"} be square" do it "#{args[5] ? "" : "not"} be square" do
assert_equal args[5], @geo.square? assert_equal args[5], @geo.square?
end end
should "report that #{args[6]} is the larger dimension" do it "report that #{args[6]} is the larger dimension" do
assert_equal args[6], @geo.larger assert_equal args[6], @geo.larger
end end
should "report that #{args[7]} is the smaller dimension" do it "report that #{args[7]} is the smaller dimension" do
assert_equal args[7], @geo.smaller assert_equal args[7], @geo.smaller
end end
should "have an aspect ratio of #{args[8]}" do it "have an aspect ratio of #{args[8]}" do
assert_in_delta args[8], @geo.aspect, 0.0001 expect(@geo.aspect).to be_within(0.0001).of(args[8])
end end
end end
end end
...@@ -219,17 +217,17 @@ class GeometryTest < Test::Unit::TestCase ...@@ -219,17 +217,17 @@ class GeometryTest < Test::Unit::TestCase
[ [100, 1000], [50, 950], "x950", "50x950+22+0" ], [ [100, 1000], [50, 950], "x950", "50x950+22+0" ],
[ [100, 1000], [50, 25], "50x", "50x25+0+237" ]]. each do |args| [ [100, 1000], [50, 25], "50x", "50x25+0+237" ]]. each do |args|
context "of #{args[0].inspect} and given a Geometry #{args[1].inspect} and sent transform_to" do context "of #{args[0].inspect} and given a Geometry #{args[1].inspect} and sent transform_to" do
setup do before do
@geo = Paperclip::Geometry.new(*args[0]) @geo = Paperclip::Geometry.new(*args[0])
@dst = Paperclip::Geometry.new(*args[1]) @dst = Paperclip::Geometry.new(*args[1])
@scale, @crop = @geo.transformation_to @dst, true @scale, @crop = @geo.transformation_to @dst, true
end end
should "be able to return the correct scaling transformation geometry #{args[2]}" do it "be able to return the correct scaling transformation geometry #{args[2]}" do
assert_equal args[2], @scale assert_equal args[2], @scale
end end
should "be able to return the correct crop transformation geometry #{args[3]}" do it "be able to return the correct crop transformation geometry #{args[3]}" do
assert_equal args[3], @crop assert_equal args[3], @crop
end end
end end
...@@ -240,14 +238,14 @@ class GeometryTest < Test::Unit::TestCase ...@@ -240,14 +238,14 @@ class GeometryTest < Test::Unit::TestCase
['600x400', {'512x512!' => [512, 512], '512x512#' => [512, 512], '512x512>' => [512, 341], '512x512<' => [600, 400], '512x512' => [512, 341]}]].each do |original_size, options| ['600x400', {'512x512!' => [512, 512], '512x512#' => [512, 512], '512x512>' => [512, 341], '512x512<' => [600, 400], '512x512' => [512, 341]}]].each do |original_size, options|
options.each_pair do |size, dimensions| options.each_pair do |size, dimensions|
context "#{original_size} resize_to #{size}" do context "#{original_size} resize_to #{size}" do
setup do before do
@source = Paperclip::Geometry.parse original_size @source = Paperclip::Geometry.parse original_size
@new_geometry = @source.resize_to size @new_geometry = @source.resize_to size
end end
should "have #{dimensions.first} width" do it "have #{dimensions.first} width" do
assert_equal dimensions.first, @new_geometry.width assert_equal dimensions.first, @new_geometry.width
end end
should "have #{dimensions.last} height" do it "have #{dimensions.last} height" do
assert_equal dimensions.last, @new_geometry.height assert_equal dimensions.last, @new_geometry.height
end end
end end
......
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
......
# encoding: utf-8 # encoding: utf-8
require 'spec_helper'
require './test/helper'
require 'open-uri' require 'open-uri'
class IntegrationTest < Test::Unit::TestCase describe 'Paperclip' do
context "Many models at once" do context "Many models at once" do
setup do before do
rebuild_model rebuild_model
@file = File.new(fixture_file("5k.png"), 'rb') @file = File.new(fixture_file("5k.png"), 'rb')
300.times do |i| 300.times do |i|
...@@ -13,9 +12,9 @@ class IntegrationTest < Test::Unit::TestCase ...@@ -13,9 +12,9 @@ class IntegrationTest < Test::Unit::TestCase
end end
end end
teardown { @file.close } # after { @file.close }
should "not exceed the open file limit" do it "not exceed the open file limit" do
assert_nothing_raised do assert_nothing_raised do
Dummy.all.each { |dummy| dummy.avatar } Dummy.all.each { |dummy| dummy.avatar }
end end
...@@ -23,7 +22,7 @@ class IntegrationTest < Test::Unit::TestCase ...@@ -23,7 +22,7 @@ class IntegrationTest < Test::Unit::TestCase
end end
context "An attachment" do context "An attachment" do
setup do before do
rebuild_model :styles => { :thumb => "50x50#" } rebuild_model :styles => { :thumb => "50x50#" }
@dummy = Dummy.new @dummy = Dummy.new
@file = File.new(fixture_file("5k.png"), 'rb') @file = File.new(fixture_file("5k.png"), 'rb')
...@@ -31,16 +30,16 @@ class IntegrationTest < Test::Unit::TestCase ...@@ -31,16 +30,16 @@ class IntegrationTest < Test::Unit::TestCase
assert @dummy.save assert @dummy.save
end end
teardown { @file.close } # after { @file.close }
should "create its thumbnails properly" do it "create its thumbnails properly" do
assert_match(/\b50x50\b/, `identify "#{@dummy.avatar.path(:thumb)}"`) assert_match(/\b50x50\b/, `identify "#{@dummy.avatar.path(:thumb)}"`)
end end
context 'reprocessing with unreadable original' do context 'reprocessing with unreadable original' do
setup { File.chmod(0000, @dummy.avatar.path) } before { File.chmod(0000, @dummy.avatar.path) }
should "not raise an error" do it "not raise an error" do
assert_nothing_raised do assert_nothing_raised do
silence_stream(STDERR) do silence_stream(STDERR) do
@dummy.avatar.reprocess! @dummy.avatar.reprocess!
...@@ -48,17 +47,17 @@ class IntegrationTest < Test::Unit::TestCase ...@@ -48,17 +47,17 @@ class IntegrationTest < Test::Unit::TestCase
end end
end end
should "return false" do it "return false" do
silence_stream(STDERR) do silence_stream(STDERR) do
assert !@dummy.avatar.reprocess! assert !@dummy.avatar.reprocess!
end end
end end
teardown { File.chmod(0644, @dummy.avatar.path) } # after { File.chmod(0644, @dummy.avatar.path) }
end end
context "redefining its attachment styles" do context "redefining its attachment styles" do
setup do before do
Dummy.class_eval do Dummy.class_eval do
has_attached_file :avatar, :styles => { :thumb => "150x25#", :dynamic => lambda { |a| '50x50#' } } has_attached_file :avatar, :styles => { :thumb => "150x25#", :dynamic => lambda { |a| '50x50#' } }
end end
...@@ -68,19 +67,19 @@ class IntegrationTest < Test::Unit::TestCase ...@@ -68,19 +67,19 @@ class IntegrationTest < Test::Unit::TestCase
@d2.save @d2.save
end end
should "create its thumbnails properly" do it "create its thumbnails properly" do
assert_match(/\b150x25\b/, `identify "#{@dummy.avatar.path(:thumb)}"`) assert_match(/\b150x25\b/, `identify "#{@dummy.avatar.path(:thumb)}"`)
assert_match(/\b50x50\b/, `identify "#{@dummy.avatar.path(:dynamic)}"`) assert_match(/\b50x50\b/, `identify "#{@dummy.avatar.path(:dynamic)}"`)
end end
should "change the timestamp" do it "change the timestamp" do
assert_not_equal @original_timestamp, @d2.avatar_updated_at assert_not_equal @original_timestamp, @d2.avatar_updated_at
end end
end end
end end
context "Attachment" do context "Attachment" do
setup do before do
@thumb_path = "tmp/public/system/dummies/avatars/000/000/001/thumb/5k.png" @thumb_path = "tmp/public/system/dummies/avatars/000/000/001/thumb/5k.png"
File.delete(@thumb_path) if File.exists?(@thumb_path) File.delete(@thumb_path) if File.exists?(@thumb_path)
rebuild_model :styles => { :thumb => "50x50#" } rebuild_model :styles => { :thumb => "50x50#" }
...@@ -89,16 +88,16 @@ class IntegrationTest < Test::Unit::TestCase ...@@ -89,16 +88,16 @@ class IntegrationTest < Test::Unit::TestCase
end end
teardown { @file.close } # after { @file.close }
should "not create the thumbnails upon saving when post-processing is disabled" do it "not create the thumbnails upon saving when post-processing is disabled" do
@dummy.avatar.post_processing = false @dummy.avatar.post_processing = false
@dummy.avatar = @file @dummy.avatar = @file
assert @dummy.save assert @dummy.save
assert_file_not_exists @thumb_path assert_file_not_exists @thumb_path
end end
should "create the thumbnails upon saving when post_processing is enabled" do it "create the thumbnails upon saving when post_processing is enabled" do
@dummy.avatar.post_processing = true @dummy.avatar.post_processing = true
@dummy.avatar = @file @dummy.avatar = @file
assert @dummy.save assert @dummy.save
...@@ -107,7 +106,7 @@ class IntegrationTest < Test::Unit::TestCase ...@@ -107,7 +106,7 @@ class IntegrationTest < Test::Unit::TestCase
end end
context "Attachment with no generated thumbnails" do context "Attachment with no generated thumbnails" do
setup do before do
@thumb_small_path = "tmp/public/system/dummies/avatars/000/000/001/thumb_small/5k.png" @thumb_small_path = "tmp/public/system/dummies/avatars/000/000/001/thumb_small/5k.png"
@thumb_large_path = "tmp/public/system/dummies/avatars/000/000/001/thumb_large/5k.png" @thumb_large_path = "tmp/public/system/dummies/avatars/000/000/001/thumb_large/5k.png"
File.delete(@thumb_small_path) if File.exists?(@thumb_small_path) File.delete(@thumb_small_path) if File.exists?(@thumb_small_path)
...@@ -122,9 +121,9 @@ class IntegrationTest < Test::Unit::TestCase ...@@ -122,9 +121,9 @@ class IntegrationTest < Test::Unit::TestCase
@dummy.avatar.post_processing = true @dummy.avatar.post_processing = true
end end
teardown { @file.close } # after { @file.close }
should "allow us to create all thumbnails in one go" do it "allow us to create all thumbnails in one go" do
assert_file_not_exists(@thumb_small_path) assert_file_not_exists(@thumb_small_path)
assert_file_not_exists(@thumb_large_path) assert_file_not_exists(@thumb_large_path)
...@@ -134,7 +133,7 @@ class IntegrationTest < Test::Unit::TestCase ...@@ -134,7 +133,7 @@ class IntegrationTest < Test::Unit::TestCase
assert_file_exists(@thumb_large_path) assert_file_exists(@thumb_large_path)
end end
should "allow us to selectively create each thumbnail" do it "allow us to selectively create each thumbnail" do
assert_file_not_exists(@thumb_small_path) assert_file_not_exists(@thumb_small_path)
assert_file_not_exists(@thumb_large_path) assert_file_not_exists(@thumb_large_path)
...@@ -148,22 +147,22 @@ class IntegrationTest < Test::Unit::TestCase ...@@ -148,22 +147,22 @@ class IntegrationTest < Test::Unit::TestCase
end end
context "A model that modifies its original" do context "A model that modifies its original" do
setup do before do
rebuild_model :styles => { :original => "2x2#" } rebuild_model :styles => { :original => "2x2#" }
@dummy = Dummy.new @dummy = Dummy.new
@file = File.new(fixture_file("5k.png"), 'rb') @file = File.new(fixture_file("5k.png"), 'rb')
@dummy.avatar = @file @dummy.avatar = @file
end end
should "report the file size of the processed file and not the original" do it "report the file size of the processed file and not the original" do
assert_not_equal File.size(@file.path), @dummy.avatar.size assert_not_equal File.size(@file.path), @dummy.avatar.size
end end
teardown { @file.close } # after { @file.close }
end end
context "A model with attachments scoped under an id" do context "A model with attachments scoped under an id" do
setup do before do
rebuild_model :styles => { :large => "100x100", rebuild_model :styles => { :large => "100x100",
:medium => "50x50" }, :medium => "50x50" },
:path => ":rails_root/tmp/:id/:attachments/:style.:extension" :path => ":rails_root/tmp/:id/:attachments/:style.:extension"
...@@ -172,35 +171,41 @@ class IntegrationTest < Test::Unit::TestCase ...@@ -172,35 +171,41 @@ class IntegrationTest < Test::Unit::TestCase
@dummy.avatar = @file @dummy.avatar = @file
end end
teardown { @file.close } # after { @file.close }
context "when saved" do context "when saved" do
setup do before do
@dummy.save @dummy.save
@saved_path = @dummy.avatar.path(:large) @saved_path = @dummy.avatar.path(:large)
end end
should "have a large file in the right place" do it "have a large file in the right place" do
assert_file_exists(@dummy.avatar.path(:large)) assert_file_exists(@dummy.avatar.path(:large))
end end
context "and deleted" do context "and deleted" do
setup do before do
@dummy.avatar.clear @dummy.avatar.clear
@dummy.save @dummy.save
end end
should "not have a large file in the right place anymore" do it "not have a large file in the right place anymore" do
assert_file_not_exists(@saved_path) assert_file_not_exists(@saved_path)
end end
should "not have its next two parent directories" do it "not have its next two parent directories" do
assert_file_not_exists(File.dirname(@saved_path)) assert_file_not_exists(File.dirname(@saved_path))
assert_file_not_exists(File.dirname(File.dirname(@saved_path))) assert_file_not_exists(File.dirname(File.dirname(@saved_path)))
end end
end
before_should "not die if an unexpected SystemCallError happens" do context 'and deleted where the delete fails' do
it "not die if an unexpected SystemCallError happens" do
FileUtils.stubs(:rmdir).raises(Errno::EPIPE) FileUtils.stubs(:rmdir).raises(Errno::EPIPE)
assert_nothing_raised do
@dummy.avatar.clear
@dummy.save
end
end end
end end
end end
...@@ -208,19 +213,19 @@ class IntegrationTest < Test::Unit::TestCase ...@@ -208,19 +213,19 @@ class IntegrationTest < Test::Unit::TestCase
[000,002,022].each do |umask| [000,002,022].each do |umask|
context "when the umask is #{umask}" do context "when the umask is #{umask}" do
setup do before do
rebuild_model rebuild_model
@dummy = Dummy.new @dummy = Dummy.new
@file = File.new(fixture_file("5k.png"), 'rb') @file = File.new(fixture_file("5k.png"), 'rb')
@umask = File.umask(umask) @umask = File.umask(umask)
end end
teardown do # after do
File.umask @umask # File.umask @umask
@file.close # @file.close
end # end
should "respect the current umask" do it "respect the current umask" do
@dummy.avatar = @file @dummy.avatar = @file
@dummy.save @dummy.save
assert_equal 0666&~umask, 0666&File.stat(@dummy.avatar.path).mode assert_equal 0666&~umask, 0666&File.stat(@dummy.avatar.path).mode
...@@ -230,17 +235,17 @@ class IntegrationTest < Test::Unit::TestCase ...@@ -230,17 +235,17 @@ class IntegrationTest < Test::Unit::TestCase
[0666,0664,0640].each do |perms| [0666,0664,0640].each do |perms|
context "when the perms are #{perms}" do context "when the perms are #{perms}" do
setup do before do
rebuild_model :override_file_permissions => perms rebuild_model :override_file_permissions => perms
@dummy = Dummy.new @dummy = Dummy.new
@file = File.new(fixture_file("5k.png"), 'rb') @file = File.new(fixture_file("5k.png"), 'rb')
end end
teardown do # after do
@file.close # @file.close
end # end
should "respect the current perms" do it "respect the current perms" do
@dummy.avatar = @file @dummy.avatar = @file
@dummy.save @dummy.save
assert_equal perms, File.stat(@dummy.avatar.path).mode & 0777 assert_equal perms, File.stat(@dummy.avatar.path).mode & 0777
...@@ -248,7 +253,7 @@ class IntegrationTest < Test::Unit::TestCase ...@@ -248,7 +253,7 @@ class IntegrationTest < Test::Unit::TestCase
end end
end end
should "skip chmod operation, when override_file_permissions is set to false (e.g. useful when using CIFS mounts)" do it "skip chmod operation, when override_file_permissions is set to false (e.g. useful when using CIFS mounts)" do
FileUtils.expects(:chmod).never FileUtils.expects(:chmod).never
rebuild_model :override_file_permissions => false rebuild_model :override_file_permissions => false
...@@ -258,7 +263,7 @@ class IntegrationTest < Test::Unit::TestCase ...@@ -258,7 +263,7 @@ class IntegrationTest < Test::Unit::TestCase
end end
context "A model with a filesystem attachment" do context "A model with a filesystem attachment" do
setup do before do
rebuild_model :styles => { :large => "300x300>", rebuild_model :styles => { :large => "300x300>",
:medium => "100x100", :medium => "100x100",
:thumb => ["32x32#", :gif] }, :thumb => ["32x32#", :gif] },
...@@ -274,9 +279,9 @@ class IntegrationTest < Test::Unit::TestCase ...@@ -274,9 +279,9 @@ class IntegrationTest < Test::Unit::TestCase
assert @dummy.save assert @dummy.save
end end
teardown { [@file, @bad_file].each(&:close) } # after { [@file, @bad_file].each(&:close) }
should "write and delete its files" do it "write and delete its files" do
[["434x66", :original], [["434x66", :original],
["300x46", :large], ["300x46", :large],
["100x15", :medium], ["100x15", :medium],
...@@ -314,7 +319,7 @@ class IntegrationTest < Test::Unit::TestCase ...@@ -314,7 +319,7 @@ class IntegrationTest < Test::Unit::TestCase
assert_nil @d2.avatar_file_name assert_nil @d2.avatar_file_name
end end
should "work exactly the same when new as when reloaded" do it "work exactly the same when new as when reloaded" do
@d2 = Dummy.find(@dummy.id) @d2 = Dummy.find(@dummy.id)
assert_equal @dummy.avatar_file_name, @d2.avatar_file_name assert_equal @dummy.avatar_file_name, @d2.avatar_file_name
...@@ -332,18 +337,18 @@ class IntegrationTest < Test::Unit::TestCase ...@@ -332,18 +337,18 @@ class IntegrationTest < Test::Unit::TestCase
end end
end end
should "not abide things that don't have adapters" do it "not abide things that don't have adapters" do
assert_raises(Paperclip::AdapterRegistry::NoHandlerError) do assert_raises(Paperclip::AdapterRegistry::NoHandlerError) do
@dummy.avatar = "not a file" @dummy.avatar = "not a file"
end end
end end
should "not be ok with bad files" do it "not be ok with bad files" do
@dummy.avatar = @bad_file @dummy.avatar = @bad_file
assert ! @dummy.valid? assert ! @dummy.valid?
end end
should "know the difference between good files, bad files, and not files when validating" do it "know the difference between good files, bad files, and not files when validating" do
Dummy.validates_attachment_presence :avatar Dummy.validates_attachment_presence :avatar
@d2 = Dummy.find(@dummy.id) @d2 = Dummy.find(@dummy.id)
@d2.avatar = @file @d2.avatar = @file
...@@ -352,7 +357,7 @@ class IntegrationTest < Test::Unit::TestCase ...@@ -352,7 +357,7 @@ class IntegrationTest < Test::Unit::TestCase
assert ! @d2.valid? assert ! @d2.valid?
end end
should "be able to reload without saving and not have the file disappear" do it "be able to reload without saving and not have the file disappear" do
@dummy.avatar = @file @dummy.avatar = @file
assert @dummy.save, @dummy.errors.full_messages.inspect assert @dummy.save, @dummy.errors.full_messages.inspect
@dummy.avatar.clear @dummy.avatar.clear
...@@ -362,16 +367,16 @@ class IntegrationTest < Test::Unit::TestCase ...@@ -362,16 +367,16 @@ class IntegrationTest < Test::Unit::TestCase
end end
context "that is assigned its file from another Paperclip attachment" do context "that is assigned its file from another Paperclip attachment" do
setup do before do
@dummy2 = Dummy.new @dummy2 = Dummy.new
@file2 = File.new(fixture_file("12k.png"), 'rb') @file2 = File.new(fixture_file("12k.png"), 'rb')
assert @dummy2.avatar = @file2 assert @dummy2.avatar = @file2
@dummy2.save @dummy2.save
end end
teardown { @file2.close } # after { @file2.close }
should "work when assigned a file" do it "work when assigned a file" do
assert_not_equal `identify -format "%wx%h" "#{@dummy.avatar.path(:original)}"`, assert_not_equal `identify -format "%wx%h" "#{@dummy.avatar.path(:original)}"`,
`identify -format "%wx%h" "#{@dummy2.avatar.path(:original)}"` `identify -format "%wx%h" "#{@dummy2.avatar.path(:original)}"`
...@@ -386,7 +391,7 @@ class IntegrationTest < Test::Unit::TestCase ...@@ -386,7 +391,7 @@ class IntegrationTest < Test::Unit::TestCase
end end
context "A model with an attachments association and a Paperclip attachment" do context "A model with an attachments association and a Paperclip attachment" do
setup do before do
Dummy.class_eval do Dummy.class_eval do
has_many :attachments, :class_name => 'Dummy' has_many :attachments, :class_name => 'Dummy'
end end
...@@ -396,15 +401,15 @@ class IntegrationTest < Test::Unit::TestCase ...@@ -396,15 +401,15 @@ class IntegrationTest < Test::Unit::TestCase
@dummy.avatar = @file @dummy.avatar = @file
end end
teardown { @file.close } # after { @file.close }
should "should not error when saving" do it "should not error when saving" do
@dummy.save! @dummy.save!
end end
end end
context "A model with an attachment with hash in file name" do context "A model with an attachment with hash in file name" do
setup do before do
@settings = { :styles => { :thumb => "50x50#" }, @settings = { :styles => { :thumb => "50x50#" },
:path => ":rails_root/public/system/:attachment/:id_partition/:style/:hash.:extension", :path => ":rails_root/public/system/:attachment/:id_partition/:style/:hash.:extension",
:url => "/system/:attachment/:id_partition/:style/:hash.:extension", :url => "/system/:attachment/:id_partition/:style/:hash.:extension",
...@@ -416,17 +421,17 @@ class IntegrationTest < Test::Unit::TestCase ...@@ -416,17 +421,17 @@ class IntegrationTest < Test::Unit::TestCase
@dummy = Dummy.create! :avatar => @file @dummy = Dummy.create! :avatar => @file
end end
teardown do # after do
@file.close # @file.close
end # end
should "be accessible" do it "be accessible" do
assert_file_exists(@dummy.avatar.path(:original)) assert_file_exists(@dummy.avatar.path(:original))
assert_file_exists(@dummy.avatar.path(:thumb)) assert_file_exists(@dummy.avatar.path(:thumb))
end end
context "when new style is added" do context "when new style is added" do
setup do before do
@dummy.avatar.options[:styles][:mini] = "25x25#" @dummy.avatar.options[:styles][:mini] = "25x25#"
@dummy.avatar.instance_variable_set :@normalized_styles, nil @dummy.avatar.instance_variable_set :@normalized_styles, nil
Time.stubs(:now => Time.now + 10) Time.stubs(:now => Time.now + 10)
...@@ -434,7 +439,7 @@ class IntegrationTest < Test::Unit::TestCase ...@@ -434,7 +439,7 @@ class IntegrationTest < Test::Unit::TestCase
@dummy.reload @dummy.reload
end end
should "make all the styles accessible" do it "make all the styles accessible" do
assert_file_exists(@dummy.avatar.path(:original)) assert_file_exists(@dummy.avatar.path(:original))
assert_file_exists(@dummy.avatar.path(:thumb)) assert_file_exists(@dummy.avatar.path(:thumb))
assert_file_exists(@dummy.avatar.path(:mini)) assert_file_exists(@dummy.avatar.path(:mini))
...@@ -464,7 +469,7 @@ class IntegrationTest < Test::Unit::TestCase ...@@ -464,7 +469,7 @@ class IntegrationTest < Test::Unit::TestCase
end end
context "A model with an S3 attachment" do context "A model with an S3 attachment" do
setup do before do
rebuild_model :styles => { :large => "300x300>", rebuild_model :styles => { :large => "300x300>",
:medium => "100x100", :medium => "100x100",
:thumb => ["32x32#", :gif], :thumb => ["32x32#", :gif],
...@@ -492,29 +497,29 @@ class IntegrationTest < Test::Unit::TestCase ...@@ -492,29 +497,29 @@ class IntegrationTest < Test::Unit::TestCase
@files_on_s3 = s3_files_for(@dummy.avatar) @files_on_s3 = s3_files_for(@dummy.avatar)
end end
teardown do # after do
@file.close # @file.close
@bad_file.close # @bad_file.close
@files_on_s3.values.each(&:close) if @files_on_s3 # @files_on_s3.values.each(&:close) if @files_on_s3
end # end
context 'assigning itself to a new model' do context 'assigning itself to a new model' do
setup do before do
@d2 = Dummy.new @d2 = Dummy.new
@d2.avatar = @dummy.avatar @d2.avatar = @dummy.avatar
@d2.save @d2.save
end end
should "have the same name as the old file" do it "have the same name as the old file" do
assert_equal @d2.avatar.original_filename, @dummy.avatar.original_filename assert_equal @d2.avatar.original_filename, @dummy.avatar.original_filename
end end
end end
should "have the same contents as the original" do it "have the same contents as the original" do
assert_equal @file.read, @files_on_s3[:original].read assert_equal @file.read, @files_on_s3[:original].read
end end
should "write and delete its files" do it "write and delete its files" do
[["434x66", :original], [["434x66", :original],
["300x46", :large], ["300x46", :large],
["100x15", :medium], ["100x15", :medium],
...@@ -546,7 +551,7 @@ class IntegrationTest < Test::Unit::TestCase ...@@ -546,7 +551,7 @@ class IntegrationTest < Test::Unit::TestCase
assert_nil @d2.avatar_file_name assert_nil @d2.avatar_file_name
end end
should "work exactly the same when new as when reloaded" do it "work exactly the same when new as when reloaded" do
@d2 = Dummy.find(@dummy.id) @d2 = Dummy.find(@dummy.id)
assert_equal @dummy.avatar_file_name, @d2.avatar_file_name assert_equal @dummy.avatar_file_name, @d2.avatar_file_name
...@@ -570,7 +575,7 @@ class IntegrationTest < Test::Unit::TestCase ...@@ -570,7 +575,7 @@ class IntegrationTest < Test::Unit::TestCase
end end
end end
should "know the difference between good files, bad files, and nil" do it "know the difference between good files, bad files, and nil" do
@dummy.avatar = @bad_file @dummy.avatar = @bad_file
assert ! @dummy.valid? assert ! @dummy.valid?
@dummy.avatar = nil @dummy.avatar = nil
...@@ -586,7 +591,7 @@ class IntegrationTest < Test::Unit::TestCase ...@@ -586,7 +591,7 @@ class IntegrationTest < Test::Unit::TestCase
assert ! @d2.valid? assert ! @d2.valid?
end end
should "be able to reload without saving and not have the file disappear" do it "be able to reload without saving and not have the file disappear" do
@dummy.avatar = @file @dummy.avatar = @file
assert @dummy.save assert @dummy.save
@dummy.avatar = nil @dummy.avatar = nil
...@@ -595,28 +600,28 @@ class IntegrationTest < Test::Unit::TestCase ...@@ -595,28 +600,28 @@ class IntegrationTest < Test::Unit::TestCase
assert_equal "5k.png", @dummy.avatar_file_name assert_equal "5k.png", @dummy.avatar_file_name
end end
should "have the right content type" do it "have the right content type" do
headers = s3_headers_for(@dummy.avatar, :original) headers = s3_headers_for(@dummy.avatar, :original)
assert_equal 'image/png', headers['content-type'] assert_equal 'image/png', headers['content-type']
end end
should "have the right style-specific headers" do it "have the right style-specific headers" do
headers = s3_headers_for(@dummy.avatar, :custom) headers = s3_headers_for(@dummy.avatar, :custom)
assert_equal 'max-age=31557600', headers['cache-control'] assert_equal 'max-age=31557600', headers['cache-control']
end end
should "have the right style-specific metadata" do it "have the right style-specific metadata" do
headers = s3_headers_for(@dummy.avatar, :custom) headers = s3_headers_for(@dummy.avatar, :custom)
assert_equal 'bar', headers['x-amz-meta-foo'] assert_equal 'bar', headers['x-amz-meta-foo']
end end
context "with non-english character in the file name" do context "with non-english character in the file name" do
setup do before do
@file.stubs(:original_filename).returns("クリップ.png") @file.stubs(:original_filename).returns("クリップ.png")
@dummy.avatar = @file @dummy.avatar = @file
end end
should "not raise any error" do it "not raise any error" do
@dummy.save! @dummy.save!
end end
end end
...@@ -624,14 +629,14 @@ class IntegrationTest < Test::Unit::TestCase ...@@ -624,14 +629,14 @@ class IntegrationTest < Test::Unit::TestCase
end end
context "Copying attachments between models" do context "Copying attachments between models" do
setup do before do
rebuild_model rebuild_model
@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 "succeed when original attachment is a file" do it "succeed when original attachment is a file" do
original = Dummy.new original = Dummy.new
original.avatar = @file original.avatar = @file
assert original.save assert original.save
...@@ -643,7 +648,7 @@ class IntegrationTest < Test::Unit::TestCase ...@@ -643,7 +648,7 @@ class IntegrationTest < Test::Unit::TestCase
assert copy.avatar.present? assert copy.avatar.present?
end end
should "succeed when original attachment is empty" do it "succeed when original attachment is empty" do
original = Dummy.create! original = Dummy.create!
copy = Dummy.new copy = Dummy.new
......
require './test/helper' require 'spec_helper'
class InterpolationsTest < Test::Unit::TestCase describe Paperclip::Interpolations do
should "return all methods but the infrastructure when sent #all" do it "return all methods but the infrastructure when sent #all" do
methods = Paperclip::Interpolations.all methods = Paperclip::Interpolations.all
assert ! methods.include?(:[]) assert ! methods.include?(:[])
assert ! methods.include?(:[]=) assert ! methods.include?(:[]=)
...@@ -11,39 +11,39 @@ class InterpolationsTest < Test::Unit::TestCase ...@@ -11,39 +11,39 @@ class InterpolationsTest < Test::Unit::TestCase
end end
end end
should "return the Rails.root" do it "return the Rails.root" do
assert_equal Rails.root, Paperclip::Interpolations.rails_root(:attachment, :style) assert_equal Rails.root, Paperclip::Interpolations.rails_root(:attachment, :style)
end end
should "return the Rails.env" do it "return the Rails.env" do
assert_equal Rails.env, Paperclip::Interpolations.rails_env(:attachment, :style) assert_equal Rails.env, Paperclip::Interpolations.rails_env(:attachment, :style)
end end
should "return the class of the Interpolations module when called with no params" do it "return the class of the Interpolations module when called with no params" do
assert_equal Module, Paperclip::Interpolations.class assert_equal Module, Paperclip::Interpolations.class
end end
should "return the class of the instance" do it "return the class of the instance" do
attachment = mock attachment = mock
attachment.expects(:instance).returns(attachment) attachment.expects(:instance).returns(attachment)
attachment.expects(:class).returns("Thing") attachment.expects(:class).returns("Thing")
assert_equal "things", Paperclip::Interpolations.class(attachment, :style) assert_equal "things", Paperclip::Interpolations.class(attachment, :style)
end end
should "return the basename of the file" do it "return the basename of the file" do
attachment = mock attachment = mock
attachment.expects(:original_filename).returns("one.jpg").times(2) attachment.expects(:original_filename).returns("one.jpg").times(2)
assert_equal "one", Paperclip::Interpolations.basename(attachment, :style) assert_equal "one", Paperclip::Interpolations.basename(attachment, :style)
end end
should "return the extension of the file" do it "return the extension of the file" do
attachment = mock attachment = mock
attachment.expects(:original_filename).returns("one.jpg") attachment.expects(:original_filename).returns("one.jpg")
attachment.expects(:styles).returns({}) attachment.expects(:styles).returns({})
assert_equal "jpg", Paperclip::Interpolations.extension(attachment, :style) assert_equal "jpg", Paperclip::Interpolations.extension(attachment, :style)
end end
should "return the extension of the file as the format if defined in the style" do it "return the extension of the file as the format if defined in the style" do
attachment = mock attachment = mock
attachment.expects(:original_filename).never attachment.expects(:original_filename).never
attachment.expects(:styles).twice.returns({:style => {:format => "png"}}) attachment.expects(:styles).twice.returns({:style => {:format => "png"}})
...@@ -53,7 +53,7 @@ class InterpolationsTest < Test::Unit::TestCase ...@@ -53,7 +53,7 @@ class InterpolationsTest < Test::Unit::TestCase
end end
end end
should "return the extension of the file based on the content type" do it "return the extension of the file based on the content type" do
attachment = mock attachment = mock
attachment.expects(:content_type).returns('image/jpeg') attachment.expects(:content_type).returns('image/jpeg')
attachment.expects(:styles).returns({}) attachment.expects(:styles).returns({})
...@@ -62,7 +62,7 @@ class InterpolationsTest < Test::Unit::TestCase ...@@ -62,7 +62,7 @@ class InterpolationsTest < Test::Unit::TestCase
assert_equal "jpeg", interpolations.content_type_extension(attachment, :style) assert_equal "jpeg", interpolations.content_type_extension(attachment, :style)
end end
should "return the original extension of the file if it matches a content type extension" do it "return the original extension of the file if it matches a content type extension" do
attachment = mock attachment = mock
attachment.expects(:content_type).returns('image/jpeg') attachment.expects(:content_type).returns('image/jpeg')
attachment.expects(:styles).returns({}) attachment.expects(:styles).returns({})
...@@ -71,7 +71,7 @@ class InterpolationsTest < Test::Unit::TestCase ...@@ -71,7 +71,7 @@ class InterpolationsTest < Test::Unit::TestCase
assert_equal "jpe", interpolations.content_type_extension(attachment, :style) assert_equal "jpe", interpolations.content_type_extension(attachment, :style)
end end
should "return the latter half of the content type of the extension if no match found" do it "return the latter half of the content type of the extension if no match found" do
attachment = mock attachment = mock
attachment.expects(:content_type).at_least_once().returns('not/found') attachment.expects(:content_type).at_least_once().returns('not/found')
attachment.expects(:styles).returns({}) attachment.expects(:styles).returns({})
...@@ -80,7 +80,7 @@ class InterpolationsTest < Test::Unit::TestCase ...@@ -80,7 +80,7 @@ class InterpolationsTest < Test::Unit::TestCase
assert_equal "found", interpolations.content_type_extension(attachment, :style) assert_equal "found", interpolations.content_type_extension(attachment, :style)
end end
should "return the format if defined in the style, ignoring the content type" do it "return the format if defined in the style, ignoring the content type" do
attachment = mock attachment = mock
attachment.expects(:content_type).returns('image/jpeg') attachment.expects(:content_type).returns('image/jpeg')
attachment.expects(:styles).returns({:style => {:format => "png"}}) attachment.expects(:styles).returns({:style => {:format => "png"}})
...@@ -89,78 +89,78 @@ class InterpolationsTest < Test::Unit::TestCase ...@@ -89,78 +89,78 @@ class InterpolationsTest < Test::Unit::TestCase
assert_equal "png", interpolations.content_type_extension(attachment, :style) assert_equal "png", interpolations.content_type_extension(attachment, :style)
end end
should "be able to handle numeric style names" do it "be able to handle numeric style names" do
attachment = mock( attachment = mock(
:styles => {:"4" => {:format => :expected_extension}} :styles => {:"4" => {:format => :expected_extension}}
) )
assert_equal :expected_extension, Paperclip::Interpolations.extension(attachment, 4) assert_equal :expected_extension, Paperclip::Interpolations.extension(attachment, 4)
end end
should "return the #to_param of the attachment" do it "return the #to_param of the attachment" do
attachment = mock attachment = mock
attachment.expects(:to_param).returns("23-awesome") attachment.expects(:to_param).returns("23-awesome")
attachment.expects(:instance).returns(attachment) attachment.expects(:instance).returns(attachment)
assert_equal "23-awesome", Paperclip::Interpolations.param(attachment, :style) assert_equal "23-awesome", Paperclip::Interpolations.param(attachment, :style)
end end
should "return the id of the attachment" do it "return the id of the attachment" do
attachment = mock attachment = mock
attachment.expects(:id).returns(23) attachment.expects(:id).returns(23)
attachment.expects(:instance).returns(attachment) attachment.expects(:instance).returns(attachment)
assert_equal 23, Paperclip::Interpolations.id(attachment, :style) assert_equal 23, Paperclip::Interpolations.id(attachment, :style)
end end
should "return nil for attachments to new records" do it "return nil for attachments to new records" do
attachment = mock attachment = mock
attachment.expects(:id).returns(nil) attachment.expects(:id).returns(nil)
attachment.expects(:instance).returns(attachment) attachment.expects(:instance).returns(attachment)
assert_nil Paperclip::Interpolations.id(attachment, :style) assert_nil Paperclip::Interpolations.id(attachment, :style)
end end
should "return the partitioned id of the attachment when the id is an integer" do it "return the partitioned id of the attachment when the id is an integer" do
attachment = mock attachment = mock
attachment.expects(:id).returns(23) attachment.expects(:id).returns(23)
attachment.expects(:instance).returns(attachment) attachment.expects(:instance).returns(attachment)
assert_equal "000/000/023", Paperclip::Interpolations.id_partition(attachment, :style) assert_equal "000/000/023", Paperclip::Interpolations.id_partition(attachment, :style)
end end
should "return the partitioned id of the attachment when the id is a string" do it "return the partitioned id of the attachment when the id is a string" do
attachment = mock attachment = mock
attachment.expects(:id).returns("32fnj23oio2f") attachment.expects(:id).returns("32fnj23oio2f")
attachment.expects(:instance).returns(attachment) attachment.expects(:instance).returns(attachment)
assert_equal "32f/nj2/3oi", Paperclip::Interpolations.id_partition(attachment, :style) assert_equal "32f/nj2/3oi", Paperclip::Interpolations.id_partition(attachment, :style)
end end
should "return nil for the partitioned id of an attachment to a new record (when the id is nil)" do it "return nil for the partitioned id of an attachment to a new record (when the id is nil)" do
attachment = mock attachment = mock
attachment.expects(:id).returns(nil) attachment.expects(:id).returns(nil)
attachment.expects(:instance).returns(attachment) attachment.expects(:instance).returns(attachment)
assert_nil Paperclip::Interpolations.id_partition(attachment, :style) assert_nil Paperclip::Interpolations.id_partition(attachment, :style)
end end
should "return the name of the attachment" do it "return the name of the attachment" do
attachment = mock attachment = mock
attachment.expects(:name).returns("file") attachment.expects(:name).returns("file")
assert_equal "files", Paperclip::Interpolations.attachment(attachment, :style) assert_equal "files", Paperclip::Interpolations.attachment(attachment, :style)
end end
should "return the style" do it "return the style" do
assert_equal :style, Paperclip::Interpolations.style(:attachment, :style) assert_equal :style, Paperclip::Interpolations.style(:attachment, :style)
end end
should "return the default style" do it "return the default style" do
attachment = mock attachment = mock
attachment.expects(:default_style).returns(:default_style) attachment.expects(:default_style).returns(:default_style)
assert_equal :default_style, Paperclip::Interpolations.style(attachment, nil) assert_equal :default_style, Paperclip::Interpolations.style(attachment, nil)
end end
should "reinterpolate :url" do it "reinterpolate :url" do
attachment = mock attachment = mock
attachment.expects(:url).with(:style, :timestamp => false, :escape => false).returns("1234") attachment.expects(:url).with(:style, :timestamp => false, :escape => false).returns("1234")
assert_equal "1234", Paperclip::Interpolations.url(attachment, :style) assert_equal "1234", Paperclip::Interpolations.url(attachment, :style)
end end
should "raise if infinite loop detcted reinterpolating :url" do it "raise if infinite loop detcted reinterpolating :url" do
attachment = Object.new attachment = Object.new
class << attachment class << attachment
def url(*args) def url(*args)
...@@ -170,35 +170,35 @@ class InterpolationsTest < Test::Unit::TestCase ...@@ -170,35 +170,35 @@ class InterpolationsTest < Test::Unit::TestCase
assert_raises(Paperclip::Errors::InfiniteInterpolationError){ Paperclip::Interpolations.url(attachment, :style) } assert_raises(Paperclip::Errors::InfiniteInterpolationError){ Paperclip::Interpolations.url(attachment, :style) }
end end
should "return the filename as basename.extension" do it "return the filename as basename.extension" do
attachment = mock attachment = mock
attachment.expects(:styles).returns({}) attachment.expects(:styles).returns({})
attachment.expects(:original_filename).returns("one.jpg").times(3) attachment.expects(:original_filename).returns("one.jpg").times(3)
assert_equal "one.jpg", Paperclip::Interpolations.filename(attachment, :style) assert_equal "one.jpg", Paperclip::Interpolations.filename(attachment, :style)
end end
should "return the filename as basename.extension when format supplied" do it "return the filename as basename.extension when format supplied" do
attachment = mock attachment = mock
attachment.expects(:styles).returns({:style => {:format => :png}}) attachment.expects(:styles).returns({:style => {:format => :png}})
attachment.expects(:original_filename).returns("one.jpg").times(2) attachment.expects(:original_filename).returns("one.jpg").times(2)
assert_equal "one.png", Paperclip::Interpolations.filename(attachment, :style) assert_equal "one.png", Paperclip::Interpolations.filename(attachment, :style)
end end
should "return the filename as basename when extension is blank" do it "return the filename as basename when extension is blank" do
attachment = mock attachment = mock
attachment.stubs(:styles).returns({}) attachment.stubs(:styles).returns({})
attachment.stubs(:original_filename).returns("one") attachment.stubs(:original_filename).returns("one")
assert_equal "one", Paperclip::Interpolations.filename(attachment, :style) assert_equal "one", Paperclip::Interpolations.filename(attachment, :style)
end end
should "return the basename when the extension contains regexp special characters" do it "return the basename when the extension contains regexp special characters" do
attachment = mock attachment = mock
attachment.stubs(:styles).returns({}) attachment.stubs(:styles).returns({})
attachment.stubs(:original_filename).returns("one.ab)") attachment.stubs(:original_filename).returns("one.ab)")
assert_equal "one", Paperclip::Interpolations.basename(attachment, :style) assert_equal "one", Paperclip::Interpolations.basename(attachment, :style)
end end
should "return the timestamp" do it "return the timestamp" do
now = Time.now now = Time.now
zone = 'UTC' zone = 'UTC'
attachment = mock attachment = mock
...@@ -207,28 +207,28 @@ class InterpolationsTest < Test::Unit::TestCase ...@@ -207,28 +207,28 @@ class InterpolationsTest < Test::Unit::TestCase
assert_equal now.in_time_zone(zone).to_s, Paperclip::Interpolations.timestamp(attachment, :style) assert_equal now.in_time_zone(zone).to_s, Paperclip::Interpolations.timestamp(attachment, :style)
end end
should "return updated_at" do it "return updated_at" do
attachment = mock attachment = mock
seconds_since_epoch = 1234567890 seconds_since_epoch = 1234567890
attachment.expects(:updated_at).returns(seconds_since_epoch) attachment.expects(:updated_at).returns(seconds_since_epoch)
assert_equal seconds_since_epoch, Paperclip::Interpolations.updated_at(attachment, :style) assert_equal seconds_since_epoch, Paperclip::Interpolations.updated_at(attachment, :style)
end end
should "return attachment's hash when passing both arguments" do it "return attachment's hash when passing both arguments" do
attachment = mock attachment = mock
fake_hash = "a_wicked_secure_hash" fake_hash = "a_wicked_secure_hash"
attachment.expects(:hash_key).returns(fake_hash) attachment.expects(:hash_key).returns(fake_hash)
assert_equal fake_hash, Paperclip::Interpolations.hash(attachment, :style) assert_equal fake_hash, Paperclip::Interpolations.hash(attachment, :style)
end end
should "return Object#hash when passing no argument" do it "return Object#hash when passing no argument" do
attachment = mock attachment = mock
fake_hash = "a_wicked_secure_hash" fake_hash = "a_wicked_secure_hash"
attachment.expects(:hash_key).never.returns(fake_hash) attachment.expects(:hash_key).never.returns(fake_hash)
assert_not_equal fake_hash, Paperclip::Interpolations.hash assert_not_equal fake_hash, Paperclip::Interpolations.hash
end end
should "call all expected interpolations with the given arguments" do it "call all expected interpolations with the given arguments" do
Paperclip::Interpolations.expects(:id).with(:attachment, :style).returns(1234) Paperclip::Interpolations.expects(:id).with(:attachment, :style).returns(1234)
Paperclip::Interpolations.expects(:attachment).with(:attachment, :style).returns("attachments") Paperclip::Interpolations.expects(:attachment).with(:attachment, :style).returns("attachments")
Paperclip::Interpolations.expects(:notreal).never Paperclip::Interpolations.expects(:notreal).never
......
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
Paperclip::AttachmentRegistry.clear
end
teardown do
File.unlink(Paperclip.registered_attachments_styles_path) rescue nil File.unlink(Paperclip.registered_attachments_styles_path) rescue nil
end end
should "enable to get and set path to registered styles file" do it "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 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' Paperclip.registered_attachments_styles_path = '/tmp/config/paperclip_attachments.yml'
assert_equal '/tmp/config/paperclip_attachments.yml', Paperclip.registered_attachments_styles_path assert_equal '/tmp/config/paperclip_attachments.yml', Paperclip.registered_attachments_styles_path
...@@ -22,28 +17,28 @@ class PaperclipMissingAttachmentStylesTest < Test::Unit::TestCase ...@@ -22,28 +17,28 @@ class PaperclipMissingAttachmentStylesTest < Test::Unit::TestCase
assert_equal ROOT.join('tmp/public/system/paperclip_attachments.yml').to_s, Paperclip.registered_attachments_styles_path assert_equal ROOT.join('tmp/public/system/paperclip_attachments.yml').to_s, Paperclip.registered_attachments_styles_path
end end
should "be able to get current attachment styles" do it "be able to get current attachment styles" do
assert_equal Hash.new, Paperclip.send(:current_attachments_styles) assert_equal Hash.new, Paperclip.send(:current_attachments_styles)
rebuild_model :styles => {:croppable => '600x600>', :big => '1000x1000>'} rebuild_model :styles => {:croppable => '600x600>', :big => '1000x1000>'}
expected_hash = { :Dummy => {:avatar => [:big, :croppable]}} expected_hash = { :Dummy => {:avatar => [:big, :croppable]}}
assert_equal expected_hash, Paperclip.send(:current_attachments_styles) assert_equal expected_hash, Paperclip.send(:current_attachments_styles)
end end
should "be able to save current attachment styles for further comparison" 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, YAML.load_file(Paperclip.registered_attachments_styles_path) assert_equal expected_hash, YAML.load_file(Paperclip.registered_attachments_styles_path)
end end
should "be able to read registered attachment styles from file" 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!
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, Paperclip.send(:get_registered_attachments_styles)
end end
should "be able to calculate differences between registered styles and current styles" do it "be able to calculate differences between registered styles and current styles" 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>'} rebuild_model :styles => {:thumb => 'x100', :export => 'x400>', :croppable => '600x600>', :big => '1000x1000>'}
...@@ -65,7 +60,7 @@ class PaperclipMissingAttachmentStylesTest < Test::Unit::TestCase ...@@ -65,7 +60,7 @@ class PaperclipMissingAttachmentStylesTest < Test::Unit::TestCase
assert_equal Hash.new, Paperclip.missing_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 it "be able to calculate differences when a new attachment is added to a model" 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!
...@@ -82,9 +77,8 @@ class PaperclipMissingAttachmentStylesTest < Test::Unit::TestCase ...@@ -82,9 +77,8 @@ class PaperclipMissingAttachmentStylesTest < Test::Unit::TestCase
end end
# It's impossible to build styles hash without loading from database whole bunch of records # It's impossible to build styles hash without loading from database whole bunch of records
should "skip lambda-styles" do it "skip lambda-styles" do
rebuild_model :styles => lambda{ |attachment| attachment.instance.other == 'a' ? {:thumb => "50x50#"} : {:large => "400x400"} } rebuild_model :styles => lambda{ |attachment| attachment.instance.other == 'a' ? {:thumb => "50x50#"} : {:large => "400x400"} }
assert_equal Hash.new, Paperclip.send(:current_attachments_styles) assert_equal Hash.new, Paperclip.send(:current_attachments_styles)
end 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'
require 'paperclip/schema' require 'paperclip/schema'
require 'active_support/testing/deprecation' require 'active_support/testing/deprecation'
class SchemaTest < Test::Unit::TestCase describe Paperclip::Schema do
include ActiveSupport::Testing::Deprecation include ActiveSupport::Testing::Deprecation
def setup before do
rebuild_class rebuild_class
end end
def teardown after do
Dummy.connection.drop_table :dummies rescue nil Dummy.connection.drop_table :dummies rescue nil
end end
context "within table definition" do context "within table definition" do
context "using #has_attached_file" do context "using #has_attached_file" do
setup do before do
ActiveSupport::Deprecation.silenced = false ActiveSupport::Deprecation.silenced = false
end end
should "create attachment columns" do it "create attachment columns" do
Dummy.connection.create_table :dummies, :force => true do |t| Dummy.connection.create_table :dummies, :force => true do |t|
ActiveSupport::Deprecation.silence do ActiveSupport::Deprecation.silence do
t.has_attached_file :avatar t.has_attached_file :avatar
...@@ -28,13 +28,13 @@ class SchemaTest < Test::Unit::TestCase ...@@ -28,13 +28,13 @@ class SchemaTest < Test::Unit::TestCase
columns = Dummy.columns.map{ |column| [column.name, column.type] } columns = Dummy.columns.map{ |column| [column.name, column.type] }
assert_includes columns, ['avatar_file_name', :string] expect(columns).to include(['avatar_file_name', :string])
assert_includes columns, ['avatar_content_type', :string] expect(columns).to include(['avatar_content_type', :string])
assert_includes columns, ['avatar_file_size', :integer] expect(columns).to include(['avatar_file_size', :integer])
assert_includes columns, ['avatar_updated_at', :datetime] expect(columns).to include(['avatar_updated_at', :datetime])
end end
should "display deprecation warning" do it "display deprecation warning" do
Dummy.connection.create_table :dummies, :force => true do |t| Dummy.connection.create_table :dummies, :force => true do |t|
assert_deprecated do assert_deprecated do
t.has_attached_file :avatar t.has_attached_file :avatar
...@@ -44,69 +44,69 @@ class SchemaTest < Test::Unit::TestCase ...@@ -44,69 +44,69 @@ class SchemaTest < Test::Unit::TestCase
end end
context "using #attachment" do context "using #attachment" do
setup do before do
Dummy.connection.create_table :dummies, :force => true do |t| Dummy.connection.create_table :dummies, :force => true do |t|
t.attachment :avatar t.attachment :avatar
end end
rebuild_class rebuild_class
end end
should "create attachment columns" do it "create attachment columns" do
columns = Dummy.columns.map{ |column| [column.name, column.type] } columns = Dummy.columns.map{ |column| [column.name, column.type] }
assert_includes columns, ['avatar_file_name', :string] expect(columns).to include(['avatar_file_name', :string])
assert_includes columns, ['avatar_content_type', :string] expect(columns).to include(['avatar_content_type', :string])
assert_includes columns, ['avatar_file_size', :integer] expect(columns).to include(['avatar_file_size', :integer])
assert_includes columns, ['avatar_updated_at', :datetime] expect(columns).to include(['avatar_updated_at', :datetime])
end end
end end
end end
context "within schema statement" do context "within schema statement" do
setup do before do
Dummy.connection.create_table :dummies, :force => true Dummy.connection.create_table :dummies, :force => true
end end
context "migrating up" do context "migrating up" do
context "with single attachment" do context "with single attachment" do
setup do before do
Dummy.connection.add_attachment :dummies, :avatar Dummy.connection.add_attachment :dummies, :avatar
rebuild_class rebuild_class
end end
should "create attachment columns" do it "create attachment columns" do
columns = Dummy.columns.map{ |column| [column.name, column.type] } columns = Dummy.columns.map{ |column| [column.name, column.type] }
assert_includes columns, ['avatar_file_name', :string] expect(columns).to include(['avatar_file_name', :string])
assert_includes columns, ['avatar_content_type', :string] expect(columns).to include(['avatar_content_type', :string])
assert_includes columns, ['avatar_file_size', :integer] expect(columns).to include(['avatar_file_size', :integer])
assert_includes columns, ['avatar_updated_at', :datetime] expect(columns).to include(['avatar_updated_at', :datetime])
end end
end end
context "with multiple attachments" do context "with multiple attachments" do
setup do before do
Dummy.connection.add_attachment :dummies, :avatar, :photo Dummy.connection.add_attachment :dummies, :avatar, :photo
rebuild_class rebuild_class
end end
should "create attachment columns" do it "create attachment columns" do
columns = Dummy.columns.map{ |column| [column.name, column.type] } columns = Dummy.columns.map{ |column| [column.name, column.type] }
assert_includes columns, ['avatar_file_name', :string] expect(columns).to include(['avatar_file_name', :string])
assert_includes columns, ['avatar_content_type', :string] expect(columns).to include(['avatar_content_type', :string])
assert_includes columns, ['avatar_file_size', :integer] expect(columns).to include(['avatar_file_size', :integer])
assert_includes columns, ['avatar_updated_at', :datetime] expect(columns).to include(['avatar_updated_at', :datetime])
assert_includes columns, ['photo_file_name', :string] expect(columns).to include(['photo_file_name', :string])
assert_includes columns, ['photo_content_type', :string] expect(columns).to include(['photo_content_type', :string])
assert_includes columns, ['photo_file_size', :integer] expect(columns).to include(['photo_file_size', :integer])
assert_includes columns, ['photo_updated_at', :datetime] expect(columns).to include(['photo_updated_at', :datetime])
end end
end end
context "with no attachment" do context "with no attachment" do
should "raise an error" do it "raise an error" do
assert_raise ArgumentError do assert_raises ArgumentError do
Dummy.connection.add_attachment :dummies Dummy.connection.add_attachment :dummies
rebuild_class rebuild_class
end end
...@@ -115,7 +115,7 @@ class SchemaTest < Test::Unit::TestCase ...@@ -115,7 +115,7 @@ class SchemaTest < Test::Unit::TestCase
end end
context "migrating down" do context "migrating down" do
setup do before do
Dummy.connection.change_table :dummies do |t| Dummy.connection.change_table :dummies do |t|
t.column :avatar_file_name, :string t.column :avatar_file_name, :string
t.column :avatar_content_type, :string t.column :avatar_content_type, :string
...@@ -125,10 +125,10 @@ class SchemaTest < Test::Unit::TestCase ...@@ -125,10 +125,10 @@ class SchemaTest < Test::Unit::TestCase
end end
context "using #drop_attached_file" do context "using #drop_attached_file" do
setup do before do
ActiveSupport::Deprecation.silenced = false ActiveSupport::Deprecation.silenced = false
end end
should "remove the attachment columns" do it "remove the attachment columns" do
ActiveSupport::Deprecation.silence do ActiveSupport::Deprecation.silence do
Dummy.connection.drop_attached_file :dummies, :avatar Dummy.connection.drop_attached_file :dummies, :avatar
end end
...@@ -136,13 +136,13 @@ class SchemaTest < Test::Unit::TestCase ...@@ -136,13 +136,13 @@ class SchemaTest < Test::Unit::TestCase
columns = Dummy.columns.map{ |column| [column.name, column.type] } columns = Dummy.columns.map{ |column| [column.name, column.type] }
assert_not_includes columns, ['avatar_file_name', :string] expect(columns).to_not include(['avatar_file_name', :string])
assert_not_includes columns, ['avatar_content_type', :string] expect(columns).to_not include(['avatar_content_type', :string])
assert_not_includes columns, ['avatar_file_size', :integer] expect(columns).to_not include(['avatar_file_size', :integer])
assert_not_includes columns, ['avatar_updated_at', :datetime] expect(columns).to_not include(['avatar_updated_at', :datetime])
end end
should "display a deprecation warning" do it "display a deprecation warning" do
assert_deprecated do assert_deprecated do
Dummy.connection.drop_attached_file :dummies, :avatar Dummy.connection.drop_attached_file :dummies, :avatar
end end
...@@ -151,23 +151,23 @@ class SchemaTest < Test::Unit::TestCase ...@@ -151,23 +151,23 @@ class SchemaTest < Test::Unit::TestCase
context "using #remove_attachment" do context "using #remove_attachment" do
context "with single attachment" do context "with single attachment" do
setup do before do
Dummy.connection.remove_attachment :dummies, :avatar Dummy.connection.remove_attachment :dummies, :avatar
rebuild_class rebuild_class
end end
should "remove the attachment columns" do it "remove the attachment columns" do
columns = Dummy.columns.map{ |column| [column.name, column.type] } columns = Dummy.columns.map{ |column| [column.name, column.type] }
assert_not_includes columns, ['avatar_file_name', :string] expect(columns).to_not include(['avatar_file_name', :string])
assert_not_includes columns, ['avatar_content_type', :string] expect(columns).to_not include(['avatar_content_type', :string])
assert_not_includes columns, ['avatar_file_size', :integer] expect(columns).to_not include(['avatar_file_size', :integer])
assert_not_includes columns, ['avatar_updated_at', :datetime] expect(columns).to_not include(['avatar_updated_at', :datetime])
end end
end end
context "with multiple attachments" do context "with multiple attachments" do
setup do before do
Dummy.connection.change_table :dummies do |t| Dummy.connection.change_table :dummies do |t|
t.column :photo_file_name, :string t.column :photo_file_name, :string
t.column :photo_content_type, :string t.column :photo_content_type, :string
...@@ -179,23 +179,23 @@ class SchemaTest < Test::Unit::TestCase ...@@ -179,23 +179,23 @@ class SchemaTest < Test::Unit::TestCase
rebuild_class rebuild_class
end end
should "remove the attachment columns" do it "remove the attachment columns" do
columns = Dummy.columns.map{ |column| [column.name, column.type] } columns = Dummy.columns.map{ |column| [column.name, column.type] }
assert_not_includes columns, ['avatar_file_name', :string] expect(columns).to_not include(['avatar_file_name', :string])
assert_not_includes columns, ['avatar_content_type', :string] expect(columns).to_not include(['avatar_content_type', :string])
assert_not_includes columns, ['avatar_file_size', :integer] expect(columns).to_not include(['avatar_file_size', :integer])
assert_not_includes columns, ['avatar_updated_at', :datetime] expect(columns).to_not include(['avatar_updated_at', :datetime])
assert_not_includes columns, ['photo_file_name', :string] expect(columns).to_not include(['photo_file_name', :string])
assert_not_includes columns, ['photo_content_type', :string] expect(columns).to_not include(['photo_content_type', :string])
assert_not_includes columns, ['photo_file_size', :integer] expect(columns).to_not include(['photo_file_size', :integer])
assert_not_includes columns, ['photo_updated_at', :datetime] expect(columns).to_not include(['photo_updated_at', :datetime])
end end
end end
context "with no attachment" do context "with no attachment" do
should "raise an error" do it "raise an error" do
assert_raise ArgumentError do assert_raises ArgumentError do
Dummy.connection.remove_attachment :dummies Dummy.connection.remove_attachment :dummies
end end
end end
......
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 'fog' require 'fog'
class FogTest < Test::Unit::TestCase describe Paperclip::Storage::Fog do
context "" do context "" do
setup { Fog.mock! } before { Fog.mock! }
context "with credentials provided in a path string" do context "with credentials provided in a path string" do
setup do before do
rebuild_model :styles => { :medium => "300x300>", :thumb => "100x100>" }, rebuild_model :styles => { :medium => "300x300>", :thumb => "100x100>" },
:storage => :fog, :storage => :fog,
:url => '/:attachment/:filename', :url => '/:attachment/:filename',
...@@ -17,15 +17,15 @@ class FogTest < Test::Unit::TestCase ...@@ -17,15 +17,15 @@ class FogTest < Test::Unit::TestCase
@dummy.avatar = @file @dummy.avatar = @file
end end
teardown { @file.close } after { @file.close }
should "have the proper information loading credentials from a file" do it "have the proper information loading credentials from a file" do
assert_equal @dummy.avatar.fog_credentials[:provider], 'AWS' assert_equal @dummy.avatar.fog_credentials[:provider], 'AWS'
end end
end end
context "with credentials provided in a File object" do context "with credentials provided in a File object" do
setup do before do
rebuild_model :styles => { :medium => "300x300>", :thumb => "100x100>" }, rebuild_model :styles => { :medium => "300x300>", :thumb => "100x100>" },
:storage => :fog, :storage => :fog,
:url => '/:attachment/:filename', :url => '/:attachment/:filename',
...@@ -36,15 +36,15 @@ class FogTest < Test::Unit::TestCase ...@@ -36,15 +36,15 @@ class FogTest < Test::Unit::TestCase
@dummy.avatar = @file @dummy.avatar = @file
end end
teardown { @file.close } after { @file.close }
should "have the proper information loading credentials from a file" do it "have the proper information loading credentials from a file" do
assert_equal @dummy.avatar.fog_credentials[:provider], 'AWS' assert_equal @dummy.avatar.fog_credentials[:provider], 'AWS'
end end
end end
context "with default values for path and url" do context "with default values for path and url" do
setup do before do
rebuild_model :styles => { :medium => "300x300>", :thumb => "100x100>" }, rebuild_model :styles => { :medium => "300x300>", :thumb => "100x100>" },
:storage => :fog, :storage => :fog,
:url => '/:attachment/:filename', :url => '/:attachment/:filename',
...@@ -59,16 +59,16 @@ class FogTest < Test::Unit::TestCase ...@@ -59,16 +59,16 @@ class FogTest < Test::Unit::TestCase
@dummy.avatar = @file @dummy.avatar = @file
end end
teardown { @file.close } after { @file.close }
should "be able to interpolate the path without blowing up" do it "be able to interpolate the path without blowing up" do
assert_equal File.expand_path(File.join(File.dirname(__FILE__), "../../tmp/public/avatars/5k.png")), assert_equal File.expand_path(File.join(File.dirname(__FILE__), "../../../tmp/public/avatars/5k.png")),
@dummy.avatar.path @dummy.avatar.path
end end
end end
context "with no path or url given and using defaults" do context "with no path or url given and using defaults" do
setup do before do
rebuild_model :styles => { :medium => "300x300>", :thumb => "100x100>" }, rebuild_model :styles => { :medium => "300x300>", :thumb => "100x100>" },
:storage => :fog, :storage => :fog,
:fog_directory => "paperclip", :fog_directory => "paperclip",
...@@ -83,15 +83,15 @@ class FogTest < Test::Unit::TestCase ...@@ -83,15 +83,15 @@ class FogTest < Test::Unit::TestCase
@dummy.avatar = @file @dummy.avatar = @file
end end
teardown { @file.close } after { @file.close }
should "have correct path and url from interpolated defaults" do it "have correct path and url from interpolated defaults" do
assert_equal "dummies/avatars/000/000/001/original/5k.png", @dummy.avatar.path assert_equal "dummies/avatars/000/000/001/original/5k.png", @dummy.avatar.path
end end
end end
context "with file params provided as lambda" do context "with file params provided as lambda" do
setup do before do
fog_file = lambda{ |a| { :custom_header => a.instance.custom_method }} fog_file = lambda{ |a| { :custom_header => a.instance.custom_method }}
klass = rebuild_model :storage => :fog, klass = rebuild_model :storage => :fog,
:fog_file => fog_file :fog_file => fog_file
...@@ -106,12 +106,12 @@ class FogTest < Test::Unit::TestCase ...@@ -106,12 +106,12 @@ class FogTest < Test::Unit::TestCase
@dummy = Dummy.new @dummy = Dummy.new
end end
should "be able to evaluate correct values for file headers" do it "be able to evaluate correct values for file headers" do
assert_equal @dummy.avatar.send(:fog_file), { :custom_header => 'foobar' } assert_equal @dummy.avatar.send(:fog_file), { :custom_header => 'foobar' }
end end
end end
setup do before do
@fog_directory = 'papercliptests' @fog_directory = 'papercliptests'
@credentials = { @credentials = {
...@@ -137,25 +137,25 @@ class FogTest < Test::Unit::TestCase ...@@ -137,25 +137,25 @@ class FogTest < Test::Unit::TestCase
rebuild_model(@options) rebuild_model(@options)
end end
should "be extended by the Fog module" do it "be extended by the Fog module" do
assert Dummy.new.avatar.is_a?(Paperclip::Storage::Fog) assert Dummy.new.avatar.is_a?(Paperclip::Storage::Fog)
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 = Dummy.new @dummy = Dummy.new
@dummy.avatar = @file @dummy.avatar = @file
end end
teardown do after do
@file.close @file.close
directory = @connection.directories.new(:key => @fog_directory) directory = @connection.directories.new(:key => @fog_directory)
directory.files.each {|file| file.destroy} directory.files.each {|file| file.destroy}
directory.destroy directory.destroy
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
...@@ -163,14 +163,14 @@ class FogTest < Test::Unit::TestCase ...@@ -163,14 +163,14 @@ class FogTest < 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 'be able to be copied to a local file' do it 'be able to be copied to a local file' do
@dummy.save @dummy.save
tempfile = Tempfile.new("known_location") tempfile = Tempfile.new("known_location")
tempfile.binmode tempfile.binmode
...@@ -181,7 +181,7 @@ class FogTest < Test::Unit::TestCase ...@@ -181,7 +181,7 @@ class FogTest < Test::Unit::TestCase
tempfile.close tempfile.close
end end
should "pass the content type to the Fog::Storage::AWS::Files instance" do it "pass the content type to the Fog::Storage::AWS::Files instance" do
Fog::Storage::AWS::Files.any_instance.expects(:create).with do |hash| Fog::Storage::AWS::Files.any_instance.expects(:create).with do |hash|
hash[:content_type] hash[:content_type]
end end
...@@ -189,50 +189,50 @@ class FogTest < Test::Unit::TestCase ...@@ -189,50 +189,50 @@ class FogTest < Test::Unit::TestCase
end end
context "without a bucket" do context "without a bucket" do
setup do before do
@connection.directories.get(@fog_directory).destroy @connection.directories.get(@fog_directory).destroy
end end
should "create the bucket" do it "create the bucket" do
assert @dummy.save assert @dummy.save
assert @connection.directories.get(@fog_directory) assert @connection.directories.get(@fog_directory)
end end
end end
context "with a bucket" do context "with a bucket" do
should "succeed" do it "succeed" do
assert @dummy.save assert @dummy.save
end end
end end
context "without a fog_host" do context "without a fog_host" do
setup do before do
rebuild_model(@options.merge(:fog_host => nil)) rebuild_model(@options.merge(:fog_host => nil))
@dummy = Dummy.new @dummy = Dummy.new
@dummy.avatar = StringIO.new('.') @dummy.avatar = StringIO.new('.')
@dummy.save @dummy.save
end end
should "provide a public url" do it "provide a public url" do
assert !@dummy.avatar.url.nil? assert !@dummy.avatar.url.nil?
end end
end end
context "with a fog_host" do context "with a fog_host" do
setup do before do
rebuild_model(@options.merge(:fog_host => 'http://example.com')) rebuild_model(@options.merge(:fog_host => 'http://example.com'))
@dummy = Dummy.new @dummy = Dummy.new
@dummy.avatar = StringIO.new(".\n") @dummy.avatar = StringIO.new(".\n")
@dummy.save @dummy.save
end end
should "provide a public url" do it "provide a public url" do
assert @dummy.avatar.url =~ /^http:\/\/example\.com\/avatars\/data\.txt\?\d*$/ assert @dummy.avatar.url =~ /^http:\/\/example\.com\/avatars\/data\.txt\?\d*$/
end end
end end
context "with a fog_host that includes a wildcard placeholder" do context "with a fog_host that includes a wildcard placeholder" do
setup do before do
rebuild_model( rebuild_model(
:fog_directory => @fog_directory, :fog_directory => @fog_directory,
:fog_credentials => @credentials, :fog_credentials => @credentials,
...@@ -245,27 +245,27 @@ class FogTest < Test::Unit::TestCase ...@@ -245,27 +245,27 @@ class FogTest < Test::Unit::TestCase
@dummy.save @dummy.save
end end
should "provide a public url" do it "provide a public url" do
assert @dummy.avatar.url =~ /^http:\/\/img[0123]\.example\.com\/avatars\/data\.txt\?\d*$/ assert @dummy.avatar.url =~ /^http:\/\/img[0123]\.example\.com\/avatars\/data\.txt\?\d*$/
end end
end end
context "with fog_public set to false" do context "with fog_public set to false" do
setup do before do
rebuild_model(@options.merge(:fog_public => false)) rebuild_model(@options.merge(:fog_public => false))
@dummy = Dummy.new @dummy = Dummy.new
@dummy.avatar = StringIO.new('.') @dummy.avatar = StringIO.new('.')
@dummy.save @dummy.save
end end
should 'set the @fog_public instance variable to false' do it 'set the @fog_public instance variable to false' do
assert_equal false, @dummy.avatar.instance_variable_get('@options')[:fog_public] assert_equal false, @dummy.avatar.instance_variable_get('@options')[:fog_public]
assert_equal false, @dummy.avatar.fog_public assert_equal false, @dummy.avatar.fog_public
end end
end end
context "with styles set and fog_public set to false" do context "with styles set and fog_public set to false" do
setup do before do
rebuild_model(@options.merge(:fog_public => false, :styles => { :medium => "300x300>", :thumb => "100x100>" })) rebuild_model(@options.merge(:fog_public => false, :styles => { :medium => "300x300>", :thumb => "100x100>" }))
@file = File.new(fixture_file('5k.png'), 'rb') @file = File.new(fixture_file('5k.png'), 'rb')
@dummy = Dummy.new @dummy = Dummy.new
...@@ -273,14 +273,14 @@ class FogTest < Test::Unit::TestCase ...@@ -273,14 +273,14 @@ class FogTest < Test::Unit::TestCase
@dummy.save @dummy.save
end end
should 'set the @fog_public for a particular style to false' do it 'set the @fog_public for a particular style to false' do
assert_equal false, @dummy.avatar.instance_variable_get('@options')[:fog_public] assert_equal false, @dummy.avatar.instance_variable_get('@options')[:fog_public]
assert_equal false, @dummy.avatar.fog_public(:thumb) assert_equal false, @dummy.avatar.fog_public(:thumb)
end end
end end
context "with styles set and fog_public set per-style" do context "with styles set and fog_public set per-style" do
setup do before do
rebuild_model(@options.merge(:fog_public => { :medium => false, :thumb => true}, :styles => { :medium => "300x300>", :thumb => "100x100>" })) rebuild_model(@options.merge(:fog_public => { :medium => false, :thumb => true}, :styles => { :medium => "300x300>", :thumb => "100x100>" }))
@file = File.new(fixture_file('5k.png'), 'rb') @file = File.new(fixture_file('5k.png'), 'rb')
@dummy = Dummy.new @dummy = Dummy.new
...@@ -288,37 +288,37 @@ class FogTest < Test::Unit::TestCase ...@@ -288,37 +288,37 @@ class FogTest < Test::Unit::TestCase
@dummy.save @dummy.save
end end
should 'set the fog_public for a particular style to correct value' do it 'set the fog_public for a particular style to correct value' do
assert_equal false, @dummy.avatar.fog_public(:medium) assert_equal false, @dummy.avatar.fog_public(:medium)
assert_equal true, @dummy.avatar.fog_public(:thumb) assert_equal true, @dummy.avatar.fog_public(:thumb)
end end
end end
context "with fog_public not set" do context "with fog_public not set" do
setup do before do
rebuild_model(@options) rebuild_model(@options)
@dummy = Dummy.new @dummy = Dummy.new
@dummy.avatar = StringIO.new('.') @dummy.avatar = StringIO.new('.')
@dummy.save @dummy.save
end end
should "default fog_public to true" do it "default fog_public to true" do
assert_equal true, @dummy.avatar.fog_public assert_equal true, @dummy.avatar.fog_public
end end
end end
context "with a valid bucket name for a subdomain" do context "with a valid bucket name for a subdomain" do
should "provide an url in subdomain style" do it "provide an url in subdomain style" do
assert_match(/^https:\/\/papercliptests.s3.amazonaws.com\/avatars\/5k.png/, @dummy.avatar.url) assert_match(/^https:\/\/papercliptests.s3.amazonaws.com\/avatars\/5k.png/, @dummy.avatar.url)
end end
should "provide an url that expires in subdomain style" do it "provide an url that expires in subdomain style" do
assert_match(/^http:\/\/papercliptests.s3.amazonaws.com\/avatars\/5k.png\?AWSAccessKeyId=.+$/, @dummy.avatar.expiring_url) assert_match(/^http:\/\/papercliptests.s3.amazonaws.com\/avatars\/5k.png\?AWSAccessKeyId=.+$/, @dummy.avatar.expiring_url)
end end
end end
context "generating an expiring url" do context "generating an expiring url" do
should "generate the same url when using Times and Integer offsets" do it "generate the same url when using Times and Integer offsets" do
rebuild_model(@options) rebuild_model(@options)
dummy = Dummy.new dummy = Dummy.new
dummy.avatar = StringIO.new('.') dummy.avatar = StringIO.new('.')
...@@ -326,44 +326,44 @@ class FogTest < Test::Unit::TestCase ...@@ -326,44 +326,44 @@ class FogTest < Test::Unit::TestCase
assert_equal dummy.avatar.expiring_url(1234), dummy.avatar.expiring_url(Time.now + 1234) assert_equal dummy.avatar.expiring_url(1234), dummy.avatar.expiring_url(Time.now + 1234)
end end
should 'match the default url if there is no assignment' do it 'match the default url if there is no assignment' do
dummy = Dummy.new dummy = Dummy.new
assert_equal dummy.avatar.url, dummy.avatar.expiring_url assert_equal dummy.avatar.url, dummy.avatar.expiring_url
end end
should 'match the default url when given a style if there is no assignment' do it 'match the default url when given a style if there is no assignment' do
dummy = Dummy.new dummy = Dummy.new
assert_equal dummy.avatar.url(:thumb), dummy.avatar.expiring_url(3600, :thumb) assert_equal dummy.avatar.url(:thumb), dummy.avatar.expiring_url(3600, :thumb)
end end
end end
context "with an invalid bucket name for a subdomain" do context "with an invalid bucket name for a subdomain" do
setup do before do
rebuild_model(@options.merge(:fog_directory => "this_is_invalid")) rebuild_model(@options.merge(:fog_directory => "this_is_invalid"))
@dummy = Dummy.new @dummy = Dummy.new
@dummy.avatar = @file @dummy.avatar = @file
@dummy.save @dummy.save
end end
should "not match the bucket-subdomain restrictions" do it "not match the bucket-subdomain restrictions" do
invalid_subdomains = %w(this_is_invalid in iamareallylongbucketnameiamareallylongbucketnameiamareallylongbu invalid- inval..id inval-.id inval.-id -invalid 192.168.10.2) invalid_subdomains = %w(this_is_invalid in iamareallylongbucketnameiamareallylongbucketnameiamareallylongbu invalid- inval..id inval-.id inval.-id -invalid 192.168.10.2)
invalid_subdomains.each do |name| invalid_subdomains.each do |name|
assert_no_match Paperclip::Storage::Fog::AWS_BUCKET_SUBDOMAIN_RESTRICTON_REGEX, name assert_no_match Paperclip::Storage::Fog::AWS_BUCKET_SUBDOMAIN_RESTRICTON_REGEX, name
end end
end end
should "provide an url in folder style" do it "provide an url in folder style" do
assert_match(/^https:\/\/s3.amazonaws.com\/this_is_invalid\/avatars\/5k.png\?\d*$/, @dummy.avatar.url) assert_match(/^https:\/\/s3.amazonaws.com\/this_is_invalid\/avatars\/5k.png\?\d*$/, @dummy.avatar.url)
end end
should "provide a url that expires in folder style" do it "provide a url that expires in folder style" do
assert_match(/^http:\/\/s3.amazonaws.com\/this_is_invalid\/avatars\/5k.png\?AWSAccessKeyId=.+$/, @dummy.avatar.expiring_url) assert_match(/^http:\/\/s3.amazonaws.com\/this_is_invalid\/avatars\/5k.png\?AWSAccessKeyId=.+$/, @dummy.avatar.expiring_url)
end end
end end
context "with a proc for a bucket name evaluating a model method" do context "with a proc for a bucket name evaluating a model method" do
setup do before do
@dynamic_fog_directory = 'dynamicpaperclip' @dynamic_fog_directory = 'dynamicpaperclip'
rebuild_model(@options.merge(:fog_directory => lambda { |attachment| attachment.instance.bucket_name })) rebuild_model(@options.merge(:fog_directory => lambda { |attachment| attachment.instance.bucket_name }))
@dummy = Dummy.new @dummy = Dummy.new
...@@ -372,14 +372,14 @@ class FogTest < Test::Unit::TestCase ...@@ -372,14 +372,14 @@ class FogTest < Test::Unit::TestCase
@dummy.save @dummy.save
end end
should "have created the bucket" do it "have created the bucket" do
assert @connection.directories.get(@dynamic_fog_directory).inspect assert @connection.directories.get(@dynamic_fog_directory).inspect
end end
end end
context "with a proc for the fog_host evaluating a model method" do context "with a proc for the fog_host evaluating a model method" do
setup do before do
rebuild_model(@options.merge(:fog_host => lambda { |attachment| attachment.instance.fog_host })) rebuild_model(@options.merge(:fog_host => lambda { |attachment| attachment.instance.fog_host }))
@dummy = Dummy.new @dummy = Dummy.new
@dummy.stubs(:fog_host).returns('http://dynamicfoghost.com') @dummy.stubs(:fog_host).returns('http://dynamicfoghost.com')
...@@ -387,37 +387,37 @@ class FogTest < Test::Unit::TestCase ...@@ -387,37 +387,37 @@ class FogTest < Test::Unit::TestCase
@dummy.save @dummy.save
end end
should "provide a public url" do it "provide a public url" do
assert_match(/http:\/\/dynamicfoghost\.com/, @dummy.avatar.url) assert_match(/http:\/\/dynamicfoghost\.com/, @dummy.avatar.url)
end end
end end
context "with a custom fog_host" do context "with a custom fog_host" do
setup do before do
rebuild_model(@options.merge(:fog_host => "http://dynamicfoghost.com")) rebuild_model(@options.merge(:fog_host => "http://dynamicfoghost.com"))
@dummy = Dummy.new @dummy = Dummy.new
@dummy.avatar = @file @dummy.avatar = @file
@dummy.save @dummy.save
end end
should "provide a public url" do it "provide a public url" do
assert_match(/http:\/\/dynamicfoghost\.com/, @dummy.avatar.url) assert_match(/http:\/\/dynamicfoghost\.com/, @dummy.avatar.url)
end end
should "provide an expiring url" do it "provide an expiring url" do
assert_match(/http:\/\/dynamicfoghost\.com/, @dummy.avatar.expiring_url) assert_match(/http:\/\/dynamicfoghost\.com/, @dummy.avatar.expiring_url)
end end
context "with an invalid bucket name for a subdomain" do context "with an invalid bucket name for a subdomain" do
setup do before do
rebuild_model(@options.merge({:fog_directory => "this_is_invalid", :fog_host => "http://dynamicfoghost.com"})) rebuild_model(@options.merge({:fog_directory => "this_is_invalid", :fog_host => "http://dynamicfoghost.com"}))
@dummy = Dummy.new @dummy = Dummy.new
@dummy.avatar = @file @dummy.avatar = @file
@dummy.save @dummy.save
end end
should "provide an expiring url" do it "provide an expiring url" do
assert_match(/http:\/\/dynamicfoghost\.com/, @dummy.avatar.expiring_url) assert_match(/http:\/\/dynamicfoghost\.com/, @dummy.avatar.expiring_url)
end end
end end
...@@ -425,7 +425,7 @@ class FogTest < Test::Unit::TestCase ...@@ -425,7 +425,7 @@ class FogTest < Test::Unit::TestCase
end end
context "with a proc for the fog_credentials evaluating a model method" do context "with a proc for the fog_credentials evaluating a model method" do
setup do before do
@dynamic_fog_credentials = { @dynamic_fog_credentials = {
:provider => 'AWS', :provider => 'AWS',
:aws_access_key_id => 'DYNAMIC_ID', :aws_access_key_id => 'DYNAMIC_ID',
...@@ -438,7 +438,7 @@ class FogTest < Test::Unit::TestCase ...@@ -438,7 +438,7 @@ class FogTest < Test::Unit::TestCase
@dummy.save @dummy.save
end end
should "provide a public url" do it "provide a public url" do
assert_equal @dummy.avatar.fog_credentials, @dynamic_fog_credentials assert_equal @dummy.avatar.fog_credentials, @dynamic_fog_credentials
end end
end end
...@@ -447,7 +447,7 @@ class FogTest < Test::Unit::TestCase ...@@ -447,7 +447,7 @@ class FogTest < Test::Unit::TestCase
end end
context "when using local storage" do context "when using local storage" do
setup do before do
Fog.unmock! Fog.unmock!
rebuild_model :styles => { :medium => "300x300>", :thumb => "100x100>" }, rebuild_model :styles => { :medium => "300x300>", :thumb => "100x100>" },
:storage => :fog, :storage => :fog,
...@@ -461,12 +461,12 @@ class FogTest < Test::Unit::TestCase ...@@ -461,12 +461,12 @@ class FogTest < Test::Unit::TestCase
@dummy.avatar = @file @dummy.avatar = @file
end end
teardown do after do
@file.close @file.close
Fog.mock! Fog.mock!
end end
should "return the public url in place of the expiring url" do it "return the public url in place of the expiring url" do
assert_match @dummy.avatar.public_url, @dummy.avatar.expiring_url assert_match @dummy.avatar.public_url, @dummy.avatar.expiring_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
......
require './test/helper' require 'spec_helper'
require 'aws' require 'aws-sdk'
class S3Test < Test::Unit::TestCase describe Paperclip::Storage::S3 do
def rails_env(env) before do
silence_warnings do AWS.stub!
Object.const_set(:Rails, stub('Rails', :env => env))
end
end
def setup
AWS.config(:access_key_id => "TESTKEY", :secret_access_key => "TESTSECRET", :stub_requests => true)
end
def teardown
AWS.config(:access_key_id => nil, :secret_access_key => nil, :stub_requests => nil)
end end
context "Parsing S3 credentials" do context "Parsing S3 credentials" do
setup do before do
@proxy_settings = {:host => "127.0.0.1", :port => 8888, :user => "foo", :password => "bar"} @proxy_settings = {:host => "127.0.0.1", :port => 8888, :user => "foo", :password => "bar"}
rebuild_model :storage => :s3, rebuild_model :storage => :s3,
:bucket => "testing", :bucket => "testing",
...@@ -28,44 +18,48 @@ class S3Test < Test::Unit::TestCase ...@@ -28,44 +18,48 @@ class S3Test < Test::Unit::TestCase
@avatar = @dummy.avatar @avatar = @dummy.avatar
end end
should "get the correct credentials when RAILS_ENV is production" do it "get the correct credentials when RAILS_ENV is production" do
rails_env("production") rails_env("production") do
assert_equal({:key => "12345"}, assert_equal({:key => "12345"},
@avatar.parse_credentials('production' => {:key => '12345'}, @avatar.parse_credentials('production' => {:key => '12345'},
:development => {:key => "54321"})) :development => {:key => "54321"}))
end end
end
should "get the correct credentials when RAILS_ENV is development" do it "get the correct credentials when RAILS_ENV is development" do
rails_env("development") rails_env("development") do
assert_equal({:key => "54321"}, assert_equal({:key => "54321"},
@avatar.parse_credentials('production' => {:key => '12345'}, @avatar.parse_credentials('production' => {:key => '12345'},
:development => {:key => "54321"})) :development => {:key => "54321"}))
end end
end
should "return the argument if the key does not exist" do it "return the argument if the key does not exist" do
rails_env("not really an env") rails_env("not really an env") do
assert_equal({:test => "12345"}, @avatar.parse_credentials(:test => "12345")) assert_equal({:test => "12345"}, @avatar.parse_credentials(:test => "12345"))
end end
end
should "support HTTP proxy settings" do it "support HTTP proxy settings" do
rails_env("development") rails_env("development") do
assert_equal(true, @avatar.using_http_proxy?) assert_equal(true, @avatar.using_http_proxy?)
assert_equal(@proxy_settings[:host], @avatar.http_proxy_host) assert_equal(@proxy_settings[:host], @avatar.http_proxy_host)
assert_equal(@proxy_settings[:port], @avatar.http_proxy_port) assert_equal(@proxy_settings[:port], @avatar.http_proxy_port)
assert_equal(@proxy_settings[:user], @avatar.http_proxy_user) assert_equal(@proxy_settings[:user], @avatar.http_proxy_user)
assert_equal(@proxy_settings[:password], @avatar.http_proxy_password) assert_equal(@proxy_settings[:password], @avatar.http_proxy_password)
end end
end
end end
context ":bucket option via :s3_credentials" do context ":bucket option via :s3_credentials" do
setup do before do
rebuild_model :storage => :s3, :s3_credentials => {:bucket => 'testing'} rebuild_model :storage => :s3, :s3_credentials => {:bucket => 'testing'}
@dummy = Dummy.new @dummy = Dummy.new
end end
should "populate #bucket_name" do it "populate #bucket_name" do
assert_equal @dummy.avatar.bucket_name, 'testing' assert_equal @dummy.avatar.bucket_name, 'testing'
end end
...@@ -73,12 +67,12 @@ class S3Test < Test::Unit::TestCase ...@@ -73,12 +67,12 @@ class S3Test < Test::Unit::TestCase
context ":bucket option" do context ":bucket option" do
setup do before do
rebuild_model :storage => :s3, :bucket => "testing", :s3_credentials => {} rebuild_model :storage => :s3, :bucket => "testing", :s3_credentials => {}
@dummy = Dummy.new @dummy = Dummy.new
end end
should "populate #bucket_name" do it "populate #bucket_name" do
assert_equal @dummy.avatar.bucket_name, 'testing' assert_equal @dummy.avatar.bucket_name, 'testing'
end end
...@@ -86,7 +80,7 @@ class S3Test < Test::Unit::TestCase ...@@ -86,7 +80,7 @@ class S3Test < Test::Unit::TestCase
context "missing :bucket option" do context "missing :bucket option" do
setup do before do
rebuild_model :storage => :s3, rebuild_model :storage => :s3,
:http_proxy => @proxy_settings, :http_proxy => @proxy_settings,
:s3_credentials => {:not => :important} :s3_credentials => {:not => :important}
...@@ -96,15 +90,14 @@ class S3Test < Test::Unit::TestCase ...@@ -96,15 +90,14 @@ class S3Test < Test::Unit::TestCase
end end
should "raise an argument error" do it "raise an argument error" do
exception = assert_raise(ArgumentError) { @dummy.save } expect { @dummy.save }.to raise_error(ArgumentError, /missing required :bucket option/)
assert_match /missing required :bucket option/, exception.message
end end
end end
context "" do context "" do
setup do before do
rebuild_model :storage => :s3, rebuild_model :storage => :s3,
:s3_credentials => {}, :s3_credentials => {},
:bucket => "bucket", :bucket => "bucket",
...@@ -114,15 +107,15 @@ class S3Test < Test::Unit::TestCase ...@@ -114,15 +107,15 @@ class S3Test < Test::Unit::TestCase
@dummy.avatar = stringy_file @dummy.avatar = stringy_file
end end
should "return a url based on an S3 path" do it "return a url based on an S3 path" do
assert_match %r{^http://s3.amazonaws.com/bucket/avatars/data.txt}, @dummy.avatar.url assert_match %r{^http://s3.amazonaws.com/bucket/avatars/data.txt}, @dummy.avatar.url
end end
should "use the correct bucket" do it "use the correct bucket" do
assert_equal "bucket", @dummy.avatar.s3_bucket.name assert_equal "bucket", @dummy.avatar.s3_bucket.name
end end
should "use the correct key" do it "use the correct key" do
assert_equal "avatars/data.txt", @dummy.avatar.s3_object.key assert_equal "avatars/data.txt", @dummy.avatar.s3_object.key
end end
end end
...@@ -130,13 +123,13 @@ class S3Test < Test::Unit::TestCase ...@@ -130,13 +123,13 @@ class S3Test < Test::Unit::TestCase
context "s3_protocol" do context "s3_protocol" do
["http", :http, ""].each do |protocol| ["http", :http, ""].each do |protocol|
context "as #{protocol.inspect}" do context "as #{protocol.inspect}" do
setup do before do
rebuild_model :storage => :s3, :s3_protocol => protocol rebuild_model :storage => :s3, :s3_protocol => protocol
@dummy = Dummy.new @dummy = Dummy.new
end end
should "return the s3_protocol in string" do it "return the s3_protocol in string" do
assert_equal protocol.to_s, @dummy.avatar.s3_protocol assert_equal protocol.to_s, @dummy.avatar.s3_protocol
end end
end end
...@@ -144,7 +137,7 @@ class S3Test < Test::Unit::TestCase ...@@ -144,7 +137,7 @@ class S3Test < Test::Unit::TestCase
end end
context ":s3_protocol => 'https'" do context ":s3_protocol => 'https'" do
setup do before do
rebuild_model :storage => :s3, rebuild_model :storage => :s3,
:s3_credentials => {}, :s3_credentials => {},
:s3_protocol => 'https', :s3_protocol => 'https',
...@@ -154,13 +147,13 @@ class S3Test < Test::Unit::TestCase ...@@ -154,13 +147,13 @@ class S3Test < Test::Unit::TestCase
@dummy.avatar = stringy_file @dummy.avatar = stringy_file
end end
should "return a url based on an S3 path" do it "return a url based on an S3 path" do
assert_match %r{^https://s3.amazonaws.com/bucket/avatars/data.txt}, @dummy.avatar.url assert_match %r{^https://s3.amazonaws.com/bucket/avatars/data.txt}, @dummy.avatar.url
end end
end end
context ":s3_protocol => :https" do context ":s3_protocol => :https" do
setup do before do
rebuild_model :storage => :s3, rebuild_model :storage => :s3,
:s3_credentials => {}, :s3_credentials => {},
:s3_protocol => :https, :s3_protocol => :https,
...@@ -170,13 +163,13 @@ class S3Test < Test::Unit::TestCase ...@@ -170,13 +163,13 @@ class S3Test < Test::Unit::TestCase
@dummy.avatar = stringy_file @dummy.avatar = stringy_file
end end
should "return a url based on an S3 path" do it "return a url based on an S3 path" do
assert_match %r{^https://s3.amazonaws.com/bucket/avatars/data.txt}, @dummy.avatar.url assert_match %r{^https://s3.amazonaws.com/bucket/avatars/data.txt}, @dummy.avatar.url
end end
end end
context ":s3_protocol => ''" do context ":s3_protocol => ''" do
setup do before do
rebuild_model :storage => :s3, rebuild_model :storage => :s3,
:s3_credentials => {}, :s3_credentials => {},
:s3_protocol => '', :s3_protocol => '',
...@@ -186,13 +179,13 @@ class S3Test < Test::Unit::TestCase ...@@ -186,13 +179,13 @@ class S3Test < Test::Unit::TestCase
@dummy.avatar = stringy_file @dummy.avatar = stringy_file
end end
should "return a url based on an S3 path" do it "return a url based on an S3 path" do
assert_match %r{^//s3.amazonaws.com/bucket/avatars/data.txt}, @dummy.avatar.url assert_match %r{^//s3.amazonaws.com/bucket/avatars/data.txt}, @dummy.avatar.url
end end
end end
context "An attachment that uses S3 for storage and has the style in the path" do context "An attachment that uses S3 for storage and has the style in the path" do
setup do before do
rebuild_model :storage => :s3, rebuild_model :storage => :s3,
:bucket => "testing", :bucket => "testing",
:path => ":attachment/:style/:basename.:extension", :path => ":attachment/:style/:basename.:extension",
...@@ -209,17 +202,17 @@ class S3Test < Test::Unit::TestCase ...@@ -209,17 +202,17 @@ class S3Test < Test::Unit::TestCase
@avatar = @dummy.avatar @avatar = @dummy.avatar
end end
should "use an S3 object based on the correct path for the default style" do it "use an S3 object based on the correct path for the default style" do
assert_equal("avatars/original/data.txt", @dummy.avatar.s3_object.key) assert_equal("avatars/original/data.txt", @dummy.avatar.s3_object.key)
end end
should "use an S3 object based on the correct path for the custom style" do it "use an S3 object based on the correct path for the custom style" do
assert_equal("avatars/thumb/data.txt", @dummy.avatar.s3_object(:thumb).key) assert_equal("avatars/thumb/data.txt", @dummy.avatar.s3_object(:thumb).key)
end end
end end
context "s3_host_name" do context "s3_host_name" do
setup do before do
rebuild_model :storage => :s3, rebuild_model :storage => :s3,
:s3_credentials => {}, :s3_credentials => {},
:bucket => "bucket", :bucket => "bucket",
...@@ -229,17 +222,17 @@ class S3Test < Test::Unit::TestCase ...@@ -229,17 +222,17 @@ class S3Test < Test::Unit::TestCase
@dummy.avatar = stringy_file @dummy.avatar = stringy_file
end end
should "return a url based on an :s3_host_name path" do it "return a url based on an :s3_host_name path" do
assert_match %r{^http://s3-ap-northeast-1.amazonaws.com/bucket/avatars/data.txt}, @dummy.avatar.url assert_match %r{^http://s3-ap-northeast-1.amazonaws.com/bucket/avatars/data.txt}, @dummy.avatar.url
end end
should "use the S3 bucket with the correct host name" do it "use the S3 bucket with the correct host name" do
assert_equal "s3-ap-northeast-1.amazonaws.com", @dummy.avatar.s3_bucket.config.s3_endpoint assert_equal "s3-ap-northeast-1.amazonaws.com", @dummy.avatar.s3_bucket.config.s3_endpoint
end end
end end
context "dynamic s3_host_name" do context "dynamic s3_host_name" do
setup do before do
rebuild_model :storage => :s3, rebuild_model :storage => :s3,
:s3_credentials => {}, :s3_credentials => {},
:bucket => "bucket", :bucket => "bucket",
...@@ -252,14 +245,14 @@ class S3Test < Test::Unit::TestCase ...@@ -252,14 +245,14 @@ class S3Test < Test::Unit::TestCase
@dummy.avatar = stringy_file @dummy.avatar = stringy_file
end end
should "use s3_host_name as a proc if available" do it "use s3_host_name as a proc if available" do
@dummy.value = "s3.something.com" @dummy.value = "s3.something.com"
assert_equal "http://s3.something.com/bucket/avatars/data.txt", @dummy.avatar.url(:original, :timestamp => false) assert_equal "http://s3.something.com/bucket/avatars/data.txt", @dummy.avatar.url(:original, :timestamp => false)
end end
end end
context "An attachment that uses S3 for storage and has styles that return different file types" do context "An attachment that uses S3 for storage and has styles that return different file types" do
setup do before do
rebuild_model :styles => { :large => ['500x500#', :jpg] }, rebuild_model :styles => { :large => ['500x500#', :jpg] },
:storage => :s3, :storage => :s3,
:bucket => "bucket", :bucket => "bucket",
...@@ -275,25 +268,25 @@ class S3Test < Test::Unit::TestCase ...@@ -275,25 +268,25 @@ class S3Test < Test::Unit::TestCase
end end
end end
should "return a url containing the correct original file mime type" do it "return a url containing the correct original file mime type" do
assert_match /.+\/5k.png/, @dummy.avatar.url assert_match /.+\/5k.png/, @dummy.avatar.url
end end
should 'use the correct key for the original file mime type' do it 'use the correct key for the original file mime type' do
assert_match /.+\/5k.png/, @dummy.avatar.s3_object.key assert_match /.+\/5k.png/, @dummy.avatar.s3_object.key
end end
should "return a url containing the correct processed file mime type" do it "return a url containing the correct processed file mime type" do
assert_match /.+\/5k.jpg/, @dummy.avatar.url(:large) assert_match /.+\/5k.jpg/, @dummy.avatar.url(:large)
end end
should "use the correct key for the processed file mime type" do it "use the correct key for the processed file mime type" do
assert_match /.+\/5k.jpg/, @dummy.avatar.s3_object(:large).key assert_match /.+\/5k.jpg/, @dummy.avatar.s3_object(:large).key
end end
end end
context "An attachment that uses S3 for storage and has a proc for styles" do context "An attachment that uses S3 for storage and has a proc for styles" do
setup do before do
rebuild_model :styles => lambda { |attachment| attachment.instance.counter; {:thumbnail => { :geometry => "50x50#", :s3_headers => {'Cache-Control' => 'max-age=31557600'}} }}, rebuild_model :styles => lambda { |attachment| attachment.instance.counter; {:thumbnail => { :geometry => "50x50#", :s3_headers => {'Cache-Control' => 'max-age=31557600'}} }},
:storage => :s3, :storage => :s3,
:bucket => "bucket", :bucket => "bucket",
...@@ -324,15 +317,15 @@ class S3Test < Test::Unit::TestCase ...@@ -324,15 +317,15 @@ class S3Test < Test::Unit::TestCase
@dummy.save @dummy.save
end end
teardown { @file.close } after { @file.close }
should "succeed" do it "succeed" do
assert_equal @dummy.counter, 7 assert_equal @dummy.counter, 7
end end
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
rebuild_model :styles => { :large => ['500x500#', :jpg] }, rebuild_model :styles => { :large => ['500x500#', :jpg] },
:storage => :s3, :storage => :s3,
:bucket => "bucket", :bucket => "bucket",
...@@ -347,17 +340,17 @@ class S3Test < Test::Unit::TestCase ...@@ -347,17 +340,17 @@ class S3Test < Test::Unit::TestCase
end end
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
context "An attachment that uses S3 for storage and has a question mark in file name" do context "An attachment that uses S3 for storage and has a question mark in file name" do
setup do before do
rebuild_model :styles => { :large => ['500x500#', :jpg] }, rebuild_model :styles => { :large => ['500x500#', :jpg] },
:storage => :s3, :storage => :s3,
:bucket => "bucket", :bucket => "bucket",
...@@ -378,17 +371,17 @@ class S3Test < Test::Unit::TestCase ...@@ -378,17 +371,17 @@ class S3Test < Test::Unit::TestCase
@dummy.save @dummy.save
end end
should "return a replaced version for path" do it "return a replaced version for path" do
assert_match /.+\/question_mark\.png/, @dummy.avatar.path assert_match /.+\/question_mark\.png/, @dummy.avatar.path
end end
should "return a replaced version for url" do it "return a replaced version for url" do
assert_match /.+\/question_mark\.png/, @dummy.avatar.url assert_match /.+\/question_mark\.png/, @dummy.avatar.url
end end
end end
context "" do context "" do
setup do before do
rebuild_model :storage => :s3, rebuild_model :storage => :s3,
:s3_credentials => {}, :s3_credentials => {},
:bucket => "bucket", :bucket => "bucket",
...@@ -398,13 +391,13 @@ class S3Test < Test::Unit::TestCase ...@@ -398,13 +391,13 @@ class S3Test < Test::Unit::TestCase
@dummy.avatar = stringy_file @dummy.avatar = stringy_file
end end
should "return a url based on an S3 subdomain" do it "return a url based on an S3 subdomain" do
assert_match %r{^http://bucket.s3.amazonaws.com/avatars/data.txt}, @dummy.avatar.url assert_match %r{^http://bucket.s3.amazonaws.com/avatars/data.txt}, @dummy.avatar.url
end end
end end
context "" do context "" do
setup do before do
rebuild_model :storage => :s3, rebuild_model :storage => :s3,
:s3_credentials => { :s3_credentials => {
:production => { :bucket => "prod_bucket" }, :production => { :bucket => "prod_bucket" },
...@@ -417,13 +410,13 @@ class S3Test < Test::Unit::TestCase ...@@ -417,13 +410,13 @@ class S3Test < Test::Unit::TestCase
@dummy.avatar = stringy_file @dummy.avatar = stringy_file
end end
should "return a url based on the host_alias" do it "return a url based on the host_alias" do
assert_match %r{^http://something.something.com/avatars/data.txt}, @dummy.avatar.url assert_match %r{^http://something.something.com/avatars/data.txt}, @dummy.avatar.url
end end
end end
context "generating a url with a proc as the host alias" do context "generating a url with a proc as the host alias" do
setup do before do
rebuild_model :storage => :s3, rebuild_model :storage => :s3,
:s3_credentials => { :bucket => "prod_bucket" }, :s3_credentials => { :bucket => "prod_bucket" },
:s3_host_alias => Proc.new{|atch| "cdn#{atch.instance.counter % 4}.example.com"}, :s3_host_alias => Proc.new{|atch| "cdn#{atch.instance.counter % 4}.example.com"},
...@@ -440,19 +433,19 @@ class S3Test < Test::Unit::TestCase ...@@ -440,19 +433,19 @@ class S3Test < Test::Unit::TestCase
@dummy.avatar = stringy_file @dummy.avatar = stringy_file
end end
should "return a url based on the host_alias" do it "return a url based on the host_alias" do
assert_match %r{^http://cdn1.example.com/avatars/data.txt}, @dummy.avatar.url assert_match %r{^http://cdn1.example.com/avatars/data.txt}, @dummy.avatar.url
assert_match %r{^http://cdn2.example.com/avatars/data.txt}, @dummy.avatar.url assert_match %r{^http://cdn2.example.com/avatars/data.txt}, @dummy.avatar.url
end end
should "still return the bucket name" do it "still return the bucket name" do
assert_equal "prod_bucket", @dummy.avatar.bucket_name assert_equal "prod_bucket", @dummy.avatar.bucket_name
end end
end end
context "" do context "" do
setup do before do
rebuild_model :storage => :s3, rebuild_model :storage => :s3,
:s3_credentials => {}, :s3_credentials => {},
:bucket => "bucket", :bucket => "bucket",
...@@ -462,14 +455,14 @@ class S3Test < Test::Unit::TestCase ...@@ -462,14 +455,14 @@ class S3Test < Test::Unit::TestCase
@dummy.avatar = stringy_file @dummy.avatar = stringy_file
end end
should "return a relative URL for Rails to calculate assets host" do it "return a relative URL for Rails to calculate assets host" do
assert_match %r{^avatars/data\.txt}, @dummy.avatar.url assert_match %r{^avatars/data\.txt}, @dummy.avatar.url
end end
end end
context "Generating a secure url with an expiration" do context "Generating a secure url with an expiration" do
setup do before do
@build_model_with_options = lambda {|options| @build_model_with_options = lambda {|options|
base_options = { base_options = {
:storage => :s3, :storage => :s3,
...@@ -487,11 +480,10 @@ class S3Test < Test::Unit::TestCase ...@@ -487,11 +480,10 @@ class S3Test < Test::Unit::TestCase
} }
end end
should "use default options" do it "use default options" do
@build_model_with_options[{}] @build_model_with_options[{}]
rails_env("production") rails_env("production") do
@dummy = Dummy.new @dummy = Dummy.new
@dummy.avatar = stringy_file @dummy.avatar = stringy_file
...@@ -501,12 +493,12 @@ class S3Test < Test::Unit::TestCase ...@@ -501,12 +493,12 @@ class S3Test < Test::Unit::TestCase
@dummy.avatar.expiring_url @dummy.avatar.expiring_url
end end
end
should "allow overriding s3_url_options" do it "allow overriding s3_url_options" do
@build_model_with_options[:s3_url_options => { :response_content_disposition => "inline" }] @build_model_with_options[:s3_url_options => { :response_content_disposition => "inline" }]
rails_env("production") rails_env("production") do
@dummy = Dummy.new @dummy = Dummy.new
@dummy.avatar = stringy_file @dummy.avatar = stringy_file
...@@ -516,12 +508,12 @@ class S3Test < Test::Unit::TestCase ...@@ -516,12 +508,12 @@ class S3Test < Test::Unit::TestCase
@dummy.avatar.expiring_url @dummy.avatar.expiring_url
end end
end
should "allow overriding s3_object options with a proc" do it "allow overriding s3_object options with a proc" do
@build_model_with_options[:s3_url_options => lambda {|attachment| { :response_content_type => attachment.avatar_content_type } }] @build_model_with_options[:s3_url_options => lambda {|attachment| { :response_content_type => attachment.avatar_content_type } }]
rails_env("production") rails_env("production") do
@dummy = Dummy.new @dummy = Dummy.new
@file = stringy_file @file = stringy_file
...@@ -539,29 +531,30 @@ class S3Test < Test::Unit::TestCase ...@@ -539,29 +531,30 @@ class S3Test < Test::Unit::TestCase
@dummy.avatar.expiring_url @dummy.avatar.expiring_url
end end
end end
end
context "#expiring_url" do context "#expiring_url" do
setup { @dummy = Dummy.new } before { @dummy = Dummy.new }
context "with no attachment" do context "with no attachment" do
setup { assert(!@dummy.avatar.exists?) } before { assert(!@dummy.avatar.exists?) }
should "return the default URL" do it "return the default URL" do
assert_equal(@dummy.avatar.url, @dummy.avatar.expiring_url) assert_equal(@dummy.avatar.url, @dummy.avatar.expiring_url)
end end
should 'generate a url for a style when a file does not exist' do it 'generate a url for a style when a file does not exist' do
assert_equal(@dummy.avatar.url(:thumb), @dummy.avatar.expiring_url(3600, :thumb)) assert_equal(@dummy.avatar.url(:thumb), @dummy.avatar.expiring_url(3600, :thumb))
end end
end end
should "generate the same url when using Times and Integer offsets" do it "generate the same url when using Times and Integer offsets" do
assert_equal @dummy.avatar.expiring_url(1234), @dummy.avatar.expiring_url(Time.now + 1234) assert_equal @dummy.avatar.expiring_url(1234), @dummy.avatar.expiring_url(Time.now + 1234)
end end
end end
context "Generating a url with an expiration for each style" do context "Generating a url with an expiration for each style" do
setup do before do
rebuild_model :storage => :s3, rebuild_model :storage => :s3,
:s3_credentials => { :s3_credentials => {
:production => { :bucket => "prod_bucket" }, :production => { :bucket => "prod_bucket" },
...@@ -572,20 +565,20 @@ class S3Test < Test::Unit::TestCase ...@@ -572,20 +565,20 @@ class S3Test < Test::Unit::TestCase
:path => ":attachment/:style/:basename.:extension", :path => ":attachment/:style/:basename.:extension",
:url => ":s3_alias_url" :url => ":s3_alias_url"
rails_env("production") rails_env("production") do
@dummy = Dummy.new @dummy = Dummy.new
@dummy.avatar = stringy_file @dummy.avatar = stringy_file
end end
end
should "should generate a url for the thumb" do it "should generate a url for the thumb" do
object = stub object = stub
@dummy.avatar.stubs(:s3_object).with(:thumb).returns(object) @dummy.avatar.stubs(:s3_object).with(:thumb).returns(object)
object.expects(:url_for).with(:read, :expires => 1800, :secure => true) object.expects(:url_for).with(:read, :expires => 1800, :secure => true)
@dummy.avatar.expiring_url(1800, :thumb) @dummy.avatar.expiring_url(1800, :thumb)
end end
should "should generate a url for the default style" do it "should generate a url for the default style" do
object = stub object = stub
@dummy.avatar.stubs(:s3_object).with(:original).returns(object) @dummy.avatar.stubs(:s3_object).with(:original).returns(object)
object.expects(:url_for).with(:read, :expires => 1800, :secure => true) object.expects(:url_for).with(:read, :expires => 1800, :secure => true)
...@@ -594,7 +587,7 @@ class S3Test < Test::Unit::TestCase ...@@ -594,7 +587,7 @@ class S3Test < Test::Unit::TestCase
end end
context "Parsing S3 credentials with a bucket in them" do context "Parsing S3 credentials with a bucket in them" do
setup do before do
rebuild_model :storage => :s3, rebuild_model :storage => :s3,
:s3_credentials => { :s3_credentials => {
:production => { :bucket => "prod_bucket" }, :production => { :bucket => "prod_bucket" },
...@@ -603,21 +596,23 @@ class S3Test < Test::Unit::TestCase ...@@ -603,21 +596,23 @@ class S3Test < Test::Unit::TestCase
@dummy = Dummy.new @dummy = Dummy.new
end end
should "get the right bucket in production" do it "get the right bucket in production" do
rails_env("production") rails_env("production") do
assert_equal "prod_bucket", @dummy.avatar.bucket_name assert_equal "prod_bucket", @dummy.avatar.bucket_name
assert_equal "prod_bucket", @dummy.avatar.s3_bucket.name assert_equal "prod_bucket", @dummy.avatar.s3_bucket.name
end end
end
should "get the right bucket in development" do it "get the right bucket in development" do
rails_env("development") rails_env("development") do
assert_equal "dev_bucket", @dummy.avatar.bucket_name assert_equal "dev_bucket", @dummy.avatar.bucket_name
assert_equal "dev_bucket", @dummy.avatar.s3_bucket.name assert_equal "dev_bucket", @dummy.avatar.s3_bucket.name
end end
end end
end
context "Parsing S3 credentials with a s3_host_name in them" do context "Parsing S3 credentials with a s3_host_name in them" do
setup do before do
rebuild_model :storage => :s3, rebuild_model :storage => :s3,
:bucket => 'testing', :bucket => 'testing',
:s3_credentials => { :s3_credentials => {
...@@ -627,68 +622,73 @@ class S3Test < Test::Unit::TestCase ...@@ -627,68 +622,73 @@ class S3Test < Test::Unit::TestCase
@dummy = Dummy.new @dummy = Dummy.new
end end
should "get the right s3_host_name in production" do it "get the right s3_host_name in production" do
rails_env("production") rails_env("production") do
assert_match %r{^s3-world-end.amazonaws.com}, @dummy.avatar.s3_host_name assert_match %r{^s3-world-end.amazonaws.com}, @dummy.avatar.s3_host_name
assert_match %r{^s3-world-end.amazonaws.com}, @dummy.avatar.s3_bucket.config.s3_endpoint assert_match %r{^s3-world-end.amazonaws.com}, @dummy.avatar.s3_bucket.config.s3_endpoint
end end
end
should "get the right s3_host_name in development" do it "get the right s3_host_name in development" do
rails_env("development") rails_env("development") do
assert_match %r{^s3-ap-northeast-1.amazonaws.com}, @dummy.avatar.s3_host_name assert_match %r{^s3-ap-northeast-1.amazonaws.com}, @dummy.avatar.s3_host_name
assert_match %r{^s3-ap-northeast-1.amazonaws.com}, @dummy.avatar.s3_bucket.config.s3_endpoint assert_match %r{^s3-ap-northeast-1.amazonaws.com}, @dummy.avatar.s3_bucket.config.s3_endpoint
end end
end
should "get the right s3_host_name if the key does not exist" do it "get the right s3_host_name if the key does not exist" do
rails_env("test") rails_env("test") do
assert_match %r{^s3.amazonaws.com}, @dummy.avatar.s3_host_name assert_match %r{^s3.amazonaws.com}, @dummy.avatar.s3_host_name
assert_match %r{^s3.amazonaws.com}, @dummy.avatar.s3_bucket.config.s3_endpoint assert_match %r{^s3.amazonaws.com}, @dummy.avatar.s3_bucket.config.s3_endpoint
end end
end end
end
context "An attachment with S3 storage" do context "An attachment with S3 storage" do
setup do before do
rebuild_model :storage => :s3, rebuild_model :storage => :s3,
:bucket => "testing", :bucket => "testing",
:path => ":attachment/:style/:basename.:extension", :path => ":attachment/:style/:basename.:extension",
:s3_credentials => { :s3_credentials => {
'access_key_id' => "12345", :aws_access_key_id => "12345",
'secret_access_key' => "54321" :aws_secret_access_key => "54321"
} }
end end
should "be extended by the S3 module" do it "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
should "not be extended by the Filesystem module" do it "not be extended by the Filesystem module" do
assert ! Dummy.new.avatar.is_a?(Paperclip::Storage::Filesystem) assert ! Dummy.new.avatar.is_a?(Paperclip::Storage::Filesystem)
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 = Dummy.new @dummy = Dummy.new
@dummy.avatar = @file @dummy.avatar = @file
end end
teardown { @file.close } after { @file.close }
should "not get a bucket to get a URL" do it "not get a bucket to get a URL" do
@dummy.avatar.expects(:s3).never @dummy.avatar.expects(:s3).never
@dummy.avatar.expects(:s3_bucket).never @dummy.avatar.expects(:s3_bucket).never
assert_match %r{^http://s3\.amazonaws\.com/testing/avatars/original/5k\.png}, @dummy.avatar.url assert_match %r{^http://s3\.amazonaws\.com/testing/avatars/original/5k\.png}, @dummy.avatar.url
end end
should "be rewinded after flush_writes" do it "be rewound after flush_writes" do
@dummy.avatar.instance_eval "def after_flush_writes; end" @dummy.avatar.instance_eval "def after_flush_writes; end"
@dummy.avatar.stubs(:s3_object).returns(stub(write: true))
files = @dummy.avatar.queued_for_write.values.each(&:read) files = @dummy.avatar.queued_for_write.values.each(&:read)
@dummy.save @dummy.save
assert files.none?(&:eof?), "Expect all the files to be rewinded." assert files.none?(&:eof?), "Expect all the files to be rewound."
end end
should "be removed after after_flush_writes" do it "be removed after after_flush_writes" do
@dummy.avatar.stubs(:s3_object).returns(stub(write: true))
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) },
...@@ -696,7 +696,7 @@ class S3Test < Test::Unit::TestCase ...@@ -696,7 +696,7 @@ class S3Test < Test::Unit::TestCase
end end
context "and saved" do context "and saved" do
setup do before do
object = stub object = stub
@dummy.avatar.stubs(:s3_object).returns(object) @dummy.avatar.stubs(:s3_object).returns(object)
object.expects(:write).with(anything, object.expects(:write).with(anything,
...@@ -705,13 +705,13 @@ class S3Test < Test::Unit::TestCase ...@@ -705,13 +705,13 @@ class S3Test < Test::Unit::TestCase
@dummy.save @dummy.save
end end
should "succeed" do it "succeed" do
assert true assert true
end end
end end
context "and saved without a bucket" do context "and saved without a bucket" do
setup do before do
AWS::S3::BucketCollection.any_instance.expects(:create).with("testing") AWS::S3::BucketCollection.any_instance.expects(:create).with("testing")
AWS::S3::S3Object.any_instance.stubs(:write). AWS::S3::S3Object.any_instance.stubs(:write).
raises(AWS::S3::Errors::NoSuchBucket.new(stub, raises(AWS::S3::Errors::NoSuchBucket.new(stub,
...@@ -721,29 +721,29 @@ class S3Test < Test::Unit::TestCase ...@@ -721,29 +721,29 @@ class S3Test < Test::Unit::TestCase
@dummy.save @dummy.save
end end
should "succeed" do it "succeed" do
assert true assert true
end end
end end
context "and remove" do context "and remove" do
setup do before do
AWS::S3::S3Object.any_instance.stubs(:exists?).returns(true) AWS::S3::S3Object.any_instance.stubs(:exists?).returns(true)
AWS::S3::S3Object.any_instance.stubs(:delete) AWS::S3::S3Object.any_instance.stubs(:delete)
@dummy.destroy @dummy.destroy
end end
should "succeed" do it "succeed" do
assert true assert true
end end
end end
context 'that the file were missing' do context 'that the file were missing' do
setup do before do
AWS::S3::S3Object.any_instance.stubs(:exists?).raises(AWS::Errors::Base) AWS::S3::S3Object.any_instance.stubs(:exists?).raises(AWS::Errors::Base)
end end
should 'return false on exists?' do it 'return false on exists?' do
assert !@dummy.avatar.exists? assert !@dummy.avatar.exists?
end end
end end
...@@ -751,13 +751,13 @@ class S3Test < Test::Unit::TestCase ...@@ -751,13 +751,13 @@ class S3Test < Test::Unit::TestCase
end end
context "An attachment with S3 storage and bucket defined as a Proc" do context "An attachment with S3 storage and bucket defined as a Proc" do
setup do before do
rebuild_model :storage => :s3, rebuild_model :storage => :s3,
:bucket => lambda { |attachment| "bucket_#{attachment.instance.other}" }, :bucket => lambda { |attachment| "bucket_#{attachment.instance.other}" },
:s3_credentials => {:not => :important} :s3_credentials => {:not => :important}
end end
should "get the right bucket name" do it "get the right bucket name" do
assert "bucket_a", Dummy.new(:other => 'a').avatar.bucket_name assert "bucket_a", Dummy.new(:other => 'a').avatar.bucket_name
assert "bucket_a", Dummy.new(:other => 'a').avatar.s3_bucket.name assert "bucket_a", Dummy.new(:other => 'a').avatar.s3_bucket.name
assert "bucket_b", Dummy.new(:other => 'b').avatar.bucket_name assert "bucket_b", Dummy.new(:other => 'b').avatar.bucket_name
...@@ -766,7 +766,7 @@ class S3Test < Test::Unit::TestCase ...@@ -766,7 +766,7 @@ class S3Test < Test::Unit::TestCase
end end
context "An attachment with S3 storage and S3 credentials defined as a Proc" do context "An attachment with S3 storage and S3 credentials defined as a Proc" do
setup do before do
rebuild_model :storage => :s3, rebuild_model :storage => :s3,
:bucket => {:not => :important}, :bucket => {:not => :important},
:s3_credentials => lambda { |attachment| :s3_credentials => lambda { |attachment|
...@@ -774,14 +774,14 @@ class S3Test < Test::Unit::TestCase ...@@ -774,14 +774,14 @@ class S3Test < Test::Unit::TestCase
} }
end end
should "get the right credentials" do it "get the right credentials" do
assert "access1234", Dummy.new(:other => '1234').avatar.s3_credentials[:access_key_id] assert "access1234", Dummy.new(:other => '1234').avatar.s3_credentials[:access_key_id]
assert "secret1234", Dummy.new(:other => '1234').avatar.s3_credentials[:secret_access_key] assert "secret1234", Dummy.new(:other => '1234').avatar.s3_credentials[:secret_access_key]
end end
end end
context "An attachment with S3 storage and S3 credentials with a :credential_provider" do context "An attachment with S3 storage and S3 credentials with a :credential_provider" do
setup do before do
class DummyCredentialProvider; end class DummyCredentialProvider; end
rebuild_model :storage => :s3, rebuild_model :storage => :s3,
...@@ -792,37 +792,37 @@ class S3Test < Test::Unit::TestCase ...@@ -792,37 +792,37 @@ class S3Test < Test::Unit::TestCase
@dummy = Dummy.new @dummy = Dummy.new
end end
should "set the credential-provider" do it "set the credential-provider" do
assert_kind_of DummyCredentialProvider, @dummy.avatar.s3_bucket.config.credential_provider expect(@dummy.avatar.s3_bucket.config.credential_provider).to be_a DummyCredentialProvider
end end
end end
context "An attachment with S3 storage and S3 credentials in an unsupported manor" do context "An attachment with S3 storage and S3 credentials in an unsupported manor" do
setup do before do
rebuild_model :storage => :s3, :bucket => "testing", :s3_credentials => ["unsupported"] rebuild_model :storage => :s3, :bucket => "testing", :s3_credentials => ["unsupported"]
@dummy = Dummy.new @dummy = Dummy.new
end end
should "not accept the credentials" do it "not accept the credentials" do
assert_raise(ArgumentError) do assert_raises(ArgumentError) do
@dummy.avatar.s3_credentials @dummy.avatar.s3_credentials
end end
end end
end end
context "An attachment with S3 storage and S3 credentials not supplied" do context "An attachment with S3 storage and S3 credentials not supplied" do
setup do before do
rebuild_model :storage => :s3, :bucket => "testing" rebuild_model :storage => :s3, :bucket => "testing"
@dummy = Dummy.new @dummy = Dummy.new
end end
should "not parse any credentials" do it "not parse any credentials" do
assert_equal({}, @dummy.avatar.s3_credentials) assert_equal({}, @dummy.avatar.s3_credentials)
end end
end end
context "An attachment with S3 storage and specific s3 headers set" do context "An attachment with S3 storage and specific s3 headers set" do
setup do before do
rebuild_model :storage => :s3, rebuild_model :storage => :s3,
:bucket => "testing", :bucket => "testing",
:path => ":attachment/:style/:basename.:extension", :path => ":attachment/:style/:basename.:extension",
...@@ -834,16 +834,16 @@ class S3Test < Test::Unit::TestCase ...@@ -834,16 +834,16 @@ class S3Test < Test::Unit::TestCase
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 = Dummy.new @dummy = Dummy.new
@dummy.avatar = @file @dummy.avatar = @file
end end
teardown { @file.close } after { @file.close }
context "and saved" do context "and saved" do
setup do before do
object = stub object = stub
@dummy.avatar.stubs(:s3_object).returns(object) @dummy.avatar.stubs(:s3_object).returns(object)
object.expects(:write).with(anything, object.expects(:write).with(anything,
...@@ -853,7 +853,7 @@ class S3Test < Test::Unit::TestCase ...@@ -853,7 +853,7 @@ class S3Test < Test::Unit::TestCase
@dummy.save @dummy.save
end end
should "succeed" do it "succeed" do
assert true assert true
end end
end end
...@@ -861,7 +861,7 @@ class S3Test < Test::Unit::TestCase ...@@ -861,7 +861,7 @@ class S3Test < Test::Unit::TestCase
end end
context "An attachment with S3 storage and metadata set using header names" do context "An attachment with S3 storage and metadata set using header names" do
setup do before do
rebuild_model :storage => :s3, rebuild_model :storage => :s3,
:bucket => "testing", :bucket => "testing",
:path => ":attachment/:style/:basename.:extension", :path => ":attachment/:style/:basename.:extension",
...@@ -873,16 +873,16 @@ class S3Test < Test::Unit::TestCase ...@@ -873,16 +873,16 @@ class S3Test < Test::Unit::TestCase
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 = Dummy.new @dummy = Dummy.new
@dummy.avatar = @file @dummy.avatar = @file
end end
teardown { @file.close } after { @file.close }
context "and saved" do context "and saved" do
setup do before do
object = stub object = stub
@dummy.avatar.stubs(:s3_object).returns(object) @dummy.avatar.stubs(:s3_object).returns(object)
object.expects(:write).with(anything, object.expects(:write).with(anything,
...@@ -892,7 +892,7 @@ class S3Test < Test::Unit::TestCase ...@@ -892,7 +892,7 @@ class S3Test < Test::Unit::TestCase
@dummy.save @dummy.save
end end
should "succeed" do it "succeed" do
assert true assert true
end end
end end
...@@ -900,7 +900,7 @@ class S3Test < Test::Unit::TestCase ...@@ -900,7 +900,7 @@ class S3Test < Test::Unit::TestCase
end end
context "An attachment with S3 storage and metadata set using the :s3_metadata option" do context "An attachment with S3 storage and metadata set using the :s3_metadata option" do
setup do before do
rebuild_model :storage => :s3, rebuild_model :storage => :s3,
:bucket => "testing", :bucket => "testing",
:path => ":attachment/:style/:basename.:extension", :path => ":attachment/:style/:basename.:extension",
...@@ -912,16 +912,16 @@ class S3Test < Test::Unit::TestCase ...@@ -912,16 +912,16 @@ class S3Test < Test::Unit::TestCase
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 = Dummy.new @dummy = Dummy.new
@dummy.avatar = @file @dummy.avatar = @file
end end
teardown { @file.close } after { @file.close }
context "and saved" do context "and saved" do
setup do before do
object = stub object = stub
@dummy.avatar.stubs(:s3_object).returns(object) @dummy.avatar.stubs(:s3_object).returns(object)
object.expects(:write).with(anything, object.expects(:write).with(anything,
...@@ -931,7 +931,7 @@ class S3Test < Test::Unit::TestCase ...@@ -931,7 +931,7 @@ class S3Test < Test::Unit::TestCase
@dummy.save @dummy.save
end end
should "succeed" do it "succeed" do
assert true assert true
end end
end end
...@@ -939,7 +939,7 @@ class S3Test < Test::Unit::TestCase ...@@ -939,7 +939,7 @@ class S3Test < Test::Unit::TestCase
end end
context "An attachment with S3 storage and storage class set using the header name" do context "An attachment with S3 storage and storage class set using the header name" do
setup do before do
rebuild_model :storage => :s3, rebuild_model :storage => :s3,
:bucket => "testing", :bucket => "testing",
:path => ":attachment/:style/:basename.:extension", :path => ":attachment/:style/:basename.:extension",
...@@ -951,16 +951,16 @@ class S3Test < Test::Unit::TestCase ...@@ -951,16 +951,16 @@ class S3Test < Test::Unit::TestCase
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 = Dummy.new @dummy = Dummy.new
@dummy.avatar = @file @dummy.avatar = @file
end end
teardown { @file.close } after { @file.close }
context "and saved" do context "and saved" do
setup do before do
object = stub object = stub
@dummy.avatar.stubs(:s3_object).returns(object) @dummy.avatar.stubs(:s3_object).returns(object)
object.expects(:write).with(anything, object.expects(:write).with(anything,
...@@ -970,7 +970,7 @@ class S3Test < Test::Unit::TestCase ...@@ -970,7 +970,7 @@ class S3Test < Test::Unit::TestCase
@dummy.save @dummy.save
end end
should "succeed" do it "succeed" do
assert true assert true
end end
end end
...@@ -979,7 +979,7 @@ class S3Test < Test::Unit::TestCase ...@@ -979,7 +979,7 @@ class S3Test < Test::Unit::TestCase
context "Can disable AES256 encryption multiple ways" do context "Can disable AES256 encryption multiple ways" do
[nil, false, ''].each do |tech| [nil, false, ''].each do |tech|
setup do before do
rebuild_model( rebuild_model(
:storage => :s3, :storage => :s3,
:bucket => "testing", :bucket => "testing",
...@@ -991,16 +991,16 @@ class S3Test < Test::Unit::TestCase ...@@ -991,16 +991,16 @@ class S3Test < Test::Unit::TestCase
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 = Dummy.new @dummy = Dummy.new
@dummy.avatar = @file @dummy.avatar = @file
end end
teardown { @file.close } after { @file.close }
context "and saved" do context "and saved" do
setup do before do
object = stub object = stub
@dummy.avatar.stubs(:s3_object).returns(object) @dummy.avatar.stubs(:s3_object).returns(object)
object.expects(:write).with(anything, object.expects(:write).with(anything,
...@@ -1009,7 +1009,7 @@ class S3Test < Test::Unit::TestCase ...@@ -1009,7 +1009,7 @@ class S3Test < Test::Unit::TestCase
@dummy.save @dummy.save
end end
should "succeed" do it "succeed" do
assert true assert true
end end
end end
...@@ -1018,7 +1018,7 @@ class S3Test < Test::Unit::TestCase ...@@ -1018,7 +1018,7 @@ class S3Test < Test::Unit::TestCase
end end
context "An attachment with S3 storage and using AES256 encryption" do context "An attachment with S3 storage and using AES256 encryption" do
setup do before do
rebuild_model :storage => :s3, rebuild_model :storage => :s3,
:bucket => "testing", :bucket => "testing",
:path => ":attachment/:style/:basename.:extension", :path => ":attachment/:style/:basename.:extension",
...@@ -1030,16 +1030,16 @@ class S3Test < Test::Unit::TestCase ...@@ -1030,16 +1030,16 @@ class S3Test < Test::Unit::TestCase
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 = Dummy.new @dummy = Dummy.new
@dummy.avatar = @file @dummy.avatar = @file
end end
teardown { @file.close } after { @file.close }
context "and saved" do context "and saved" do
setup do before do
object = stub object = stub
@dummy.avatar.stubs(:s3_object).returns(object) @dummy.avatar.stubs(:s3_object).returns(object)
object.expects(:write).with(anything, object.expects(:write).with(anything,
...@@ -1049,7 +1049,7 @@ class S3Test < Test::Unit::TestCase ...@@ -1049,7 +1049,7 @@ class S3Test < Test::Unit::TestCase
@dummy.save @dummy.save
end end
should "succeed" do it "succeed" do
assert true assert true
end end
end end
...@@ -1057,7 +1057,7 @@ class S3Test < Test::Unit::TestCase ...@@ -1057,7 +1057,7 @@ class S3Test < Test::Unit::TestCase
end end
context "An attachment with S3 storage and storage class set using the :storage_class option" do context "An attachment with S3 storage and storage class set using the :storage_class option" do
setup do before do
rebuild_model :storage => :s3, rebuild_model :storage => :s3,
:bucket => "testing", :bucket => "testing",
:path => ":attachment/:style/:basename.:extension", :path => ":attachment/:style/:basename.:extension",
...@@ -1069,16 +1069,16 @@ class S3Test < Test::Unit::TestCase ...@@ -1069,16 +1069,16 @@ class S3Test < Test::Unit::TestCase
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 = Dummy.new @dummy = Dummy.new
@dummy.avatar = @file @dummy.avatar = @file
end end
teardown { @file.close } after { @file.close }
context "and saved" do context "and saved" do
setup do before do
object = stub object = stub
@dummy.avatar.stubs(:s3_object).returns(object) @dummy.avatar.stubs(:s3_object).returns(object)
object.expects(:write).with(anything, object.expects(:write).with(anything,
...@@ -1088,7 +1088,7 @@ class S3Test < Test::Unit::TestCase ...@@ -1088,7 +1088,7 @@ class S3Test < Test::Unit::TestCase
@dummy.save @dummy.save
end end
should "succeed" do it "succeed" do
assert true assert true
end end
end end
...@@ -1096,21 +1096,21 @@ class S3Test < Test::Unit::TestCase ...@@ -1096,21 +1096,21 @@ class S3Test < Test::Unit::TestCase
end end
context "with S3 credentials supplied as Pathname" do context "with S3 credentials supplied as Pathname" do
setup do before do
ENV['S3_KEY'] = 'pathname_key' ENV['S3_KEY'] = 'pathname_key'
ENV['S3_BUCKET'] = 'pathname_bucket' ENV['S3_BUCKET'] = 'pathname_bucket'
ENV['S3_SECRET'] = 'pathname_secret' ENV['S3_SECRET'] = 'pathname_secret'
rails_env('test') rails_env('test') do
rebuild_model :storage => :s3, rebuild_model :storage => :s3,
:s3_credentials => Pathname.new(fixture_file('s3.yml')) :s3_credentials => Pathname.new(fixture_file('s3.yml'))
Dummy.delete_all Dummy.delete_all
@dummy = Dummy.new @dummy = Dummy.new
end end
end
should "parse the credentials" do it "parse the credentials" do
assert_equal 'pathname_bucket', @dummy.avatar.bucket_name assert_equal 'pathname_bucket', @dummy.avatar.bucket_name
assert_equal 'pathname_key', @dummy.avatar.s3_bucket.config.access_key_id assert_equal 'pathname_key', @dummy.avatar.s3_bucket.config.access_key_id
assert_equal 'pathname_secret', @dummy.avatar.s3_bucket.config.secret_access_key assert_equal 'pathname_secret', @dummy.avatar.s3_bucket.config.secret_access_key
...@@ -1118,13 +1118,12 @@ class S3Test < Test::Unit::TestCase ...@@ -1118,13 +1118,12 @@ class S3Test < Test::Unit::TestCase
end end
context "with S3 credentials in a YAML file" do context "with S3 credentials in a YAML file" do
setup do before do
ENV['S3_KEY'] = 'env_key' ENV['S3_KEY'] = 'env_key'
ENV['S3_BUCKET'] = 'env_bucket' ENV['S3_BUCKET'] = 'env_bucket'
ENV['S3_SECRET'] = 'env_secret' ENV['S3_SECRET'] = 'env_secret'
rails_env('test') rails_env('test') do
rebuild_model :storage => :s3, rebuild_model :storage => :s3,
:s3_credentials => File.new(fixture_file('s3.yml')) :s3_credentials => File.new(fixture_file('s3.yml'))
...@@ -1132,8 +1131,9 @@ class S3Test < Test::Unit::TestCase ...@@ -1132,8 +1131,9 @@ class S3Test < Test::Unit::TestCase
@dummy = Dummy.new @dummy = Dummy.new
end end
end
should "run the file through ERB" do it "run the file through ERB" do
assert_equal 'env_bucket', @dummy.avatar.bucket_name assert_equal 'env_bucket', @dummy.avatar.bucket_name
assert_equal 'env_key', @dummy.avatar.s3_bucket.config.access_key_id assert_equal 'env_key', @dummy.avatar.s3_bucket.config.access_key_id
assert_equal 'env_secret', @dummy.avatar.s3_bucket.config.secret_access_key assert_equal 'env_secret', @dummy.avatar.s3_bucket.config.secret_access_key
...@@ -1142,7 +1142,7 @@ class S3Test < Test::Unit::TestCase ...@@ -1142,7 +1142,7 @@ class S3Test < Test::Unit::TestCase
context "S3 Permissions" do context "S3 Permissions" do
context "defaults to :public_read" do context "defaults to :public_read" do
setup do before do
rebuild_model :storage => :s3, rebuild_model :storage => :s3,
:bucket => "testing", :bucket => "testing",
:path => ":attachment/:style/:basename.:extension", :path => ":attachment/:style/:basename.:extension",
...@@ -1153,16 +1153,16 @@ class S3Test < Test::Unit::TestCase ...@@ -1153,16 +1153,16 @@ class S3Test < Test::Unit::TestCase
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 = Dummy.new @dummy = Dummy.new
@dummy.avatar = @file @dummy.avatar = @file
end end
teardown { @file.close } after { @file.close }
context "and saved" do context "and saved" do
setup do before do
object = stub object = stub
@dummy.avatar.stubs(:s3_object).returns(object) @dummy.avatar.stubs(:s3_object).returns(object)
object.expects(:write).with(anything, object.expects(:write).with(anything,
...@@ -1171,7 +1171,7 @@ class S3Test < Test::Unit::TestCase ...@@ -1171,7 +1171,7 @@ class S3Test < Test::Unit::TestCase
@dummy.save @dummy.save
end end
should "succeed" do it "succeed" do
assert true assert true
end end
end end
...@@ -1179,7 +1179,7 @@ class S3Test < Test::Unit::TestCase ...@@ -1179,7 +1179,7 @@ class S3Test < Test::Unit::TestCase
end end
context "string permissions set" do context "string permissions set" do
setup do before do
rebuild_model :storage => :s3, rebuild_model :storage => :s3,
:bucket => "testing", :bucket => "testing",
:path => ":attachment/:style/:basename.:extension", :path => ":attachment/:style/:basename.:extension",
...@@ -1191,16 +1191,16 @@ class S3Test < Test::Unit::TestCase ...@@ -1191,16 +1191,16 @@ class S3Test < Test::Unit::TestCase
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 = Dummy.new @dummy = Dummy.new
@dummy.avatar = @file @dummy.avatar = @file
end end
teardown { @file.close } after { @file.close }
context "and saved" do context "and saved" do
setup do before do
object = stub object = stub
@dummy.avatar.stubs(:s3_object).returns(object) @dummy.avatar.stubs(:s3_object).returns(object)
object.expects(:write).with(anything, object.expects(:write).with(anything,
...@@ -1209,7 +1209,7 @@ class S3Test < Test::Unit::TestCase ...@@ -1209,7 +1209,7 @@ class S3Test < Test::Unit::TestCase
@dummy.save @dummy.save
end end
should "succeed" do it "succeed" do
assert true assert true
end end
end end
...@@ -1217,7 +1217,7 @@ class S3Test < Test::Unit::TestCase ...@@ -1217,7 +1217,7 @@ class S3Test < Test::Unit::TestCase
end end
context "hash permissions set" do context "hash permissions set" do
setup do before do
rebuild_model :storage => :s3, rebuild_model :storage => :s3,
:bucket => "testing", :bucket => "testing",
:path => ":attachment/:style/:basename.:extension", :path => ":attachment/:style/:basename.:extension",
...@@ -1235,16 +1235,16 @@ class S3Test < Test::Unit::TestCase ...@@ -1235,16 +1235,16 @@ class S3Test < Test::Unit::TestCase
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 = Dummy.new @dummy = Dummy.new
@dummy.avatar = @file @dummy.avatar = @file
end end
teardown { @file.close } after { @file.close }
context "and saved" do context "and saved" do
setup do before do
[:thumb, :original].each do |style| [:thumb, :original].each do |style|
object = stub object = stub
@dummy.avatar.stubs(:s3_object).with(style).returns(object) @dummy.avatar.stubs(:s3_object).with(style).returns(object)
...@@ -1255,7 +1255,7 @@ class S3Test < Test::Unit::TestCase ...@@ -1255,7 +1255,7 @@ class S3Test < Test::Unit::TestCase
@dummy.save @dummy.save
end end
should "succeed" do it "succeed" do
assert true assert true
end end
end end
...@@ -1263,7 +1263,7 @@ class S3Test < Test::Unit::TestCase ...@@ -1263,7 +1263,7 @@ class S3Test < Test::Unit::TestCase
end end
context "proc permission set" do context "proc permission set" do
setup do before do
rebuild_model( rebuild_model(
:storage => :s3, :storage => :s3,
:bucket => "testing", :bucket => "testing",
...@@ -1282,21 +1282,21 @@ class S3Test < Test::Unit::TestCase ...@@ -1282,21 +1282,21 @@ class S3Test < Test::Unit::TestCase
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 = Dummy.new @dummy = Dummy.new
@dummy.stubs(:private_attachment? => true) @dummy.stubs(:private_attachment? => true)
@dummy.avatar = @file @dummy.avatar = @file
end end
teardown { @file.close } after { @file.close }
context "and saved" do context "and saved" do
setup do before do
@dummy.save @dummy.save
end end
should "succeed" do it "succeed" do
assert @dummy.avatar.url().include? "https://" assert @dummy.avatar.url().include? "https://"
assert @dummy.avatar.url(:thumb).include? "http://" assert @dummy.avatar.url(:thumb).include? "http://"
end end
...@@ -1307,7 +1307,7 @@ class S3Test < Test::Unit::TestCase ...@@ -1307,7 +1307,7 @@ class S3Test < Test::Unit::TestCase
end end
context "An attachment with S3 storage and metadata set using a proc as headers" do context "An attachment with S3 storage and metadata set using a proc as headers" do
setup do before do
rebuild_model( rebuild_model(
:storage => :s3, :storage => :s3,
:bucket => "testing", :bucket => "testing",
...@@ -1326,17 +1326,17 @@ class S3Test < Test::Unit::TestCase ...@@ -1326,17 +1326,17 @@ class S3Test < Test::Unit::TestCase
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 = Dummy.new @dummy = Dummy.new
@dummy.stubs(:name => 'Custom Avatar Name.png') @dummy.stubs(:name => 'Custom Avatar Name.png')
@dummy.avatar = @file @dummy.avatar = @file
end end
teardown { @file.close } after { @file.close }
context "and saved" do context "and saved" do
setup do before do
[:thumb, :original].each do |style| [:thumb, :original].each do |style|
object = stub object = stub
@dummy.avatar.stubs(:s3_object).with(style).returns(object) @dummy.avatar.stubs(:s3_object).with(style).returns(object)
...@@ -1348,10 +1348,22 @@ class S3Test < Test::Unit::TestCase ...@@ -1348,10 +1348,22 @@ class S3Test < Test::Unit::TestCase
@dummy.save @dummy.save
end end
should "succeed" do it "succeeds" do
assert true assert true
end end
end end
end end
end end
private
def rails_env(env)
stored_env, Rails.env = Rails.env, env
begin
yield
ensure
Rails.env = stored_env
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
......
require './test/helper' require 'spec_helper'
class ThumbnailTest < Test::Unit::TestCase
describe Paperclip::Thumbnail do
context "A Paperclip Tempfile" do context "A Paperclip Tempfile" do
setup do before do
@tempfile = Paperclip::Tempfile.new(["file", ".jpg"]) @tempfile = Paperclip::Tempfile.new(["file", ".jpg"])
end end
teardown { @tempfile.close } after { @tempfile.close }
should "have its path contain a real extension" do it "have its path contain a real extension" do
assert_equal ".jpg", File.extname(@tempfile.path) assert_equal ".jpg", File.extname(@tempfile.path)
end end
should "be a real Tempfile" do it "be a real Tempfile" do
assert @tempfile.is_a?(::Tempfile) assert @tempfile.is_a?(::Tempfile)
end end
end end
context "Another Paperclip Tempfile" do context "Another Paperclip Tempfile" do
setup do before do
@tempfile = Paperclip::Tempfile.new("file") @tempfile = Paperclip::Tempfile.new("file")
end end
teardown { @tempfile.close } after { @tempfile.close }
should "not have an extension if not given one" do it "not have an extension if not given one" do
assert_equal "", File.extname(@tempfile.path) assert_equal "", File.extname(@tempfile.path)
end end
should "still be a real Tempfile" do it "still be a real Tempfile" do
assert @tempfile.is_a?(::Tempfile) assert @tempfile.is_a?(::Tempfile)
end end
end end
context "An image" do context "An image" do
setup do before do
@file = File.new(fixture_file("5k.png"), 'rb') @file = File.new(fixture_file("5k.png"), 'rb')
end end
teardown { @file.close } after { @file.close }
[["600x600>", "434x66"], [["600x600>", "434x66"],
["400x400>", "400x61"], ["400x400>", "400x61"],
["32x32<", "434x66"] ["32x32<", "434x66"]
].each do |args| ].each do |args|
context "being thumbnailed with a geometry of #{args[0]}" do context "being thumbnailed with a geometry of #{args[0]}" do
setup do before do
@thumb = Paperclip::Thumbnail.new(@file, :geometry => args[0]) @thumb = Paperclip::Thumbnail.new(@file, :geometry => args[0])
end end
should "start with dimensions of 434x66" do it "start with dimensions of 434x66" do
cmd = %Q[identify -format "%wx%h" "#{@file.path}"] cmd = %Q[identify -format "%wx%h" "#{@file.path}"]
assert_equal "434x66", `#{cmd}`.chomp assert_equal "434x66", `#{cmd}`.chomp
end end
should "report the correct target geometry" do it "report the correct target geometry" do
assert_equal args[0], @thumb.target_geometry.to_s assert_equal args[0], @thumb.target_geometry.to_s
end end
context "when made" do context "when made" do
setup do before do
@thumb_result = @thumb.make @thumb_result = @thumb.make
end end
should "be the size we expect it to be" do it "be the size we expect it to be" do
cmd = %Q[identify -format "%wx%h" "#{@thumb_result.path}"] cmd = %Q[identify -format "%wx%h" "#{@thumb_result.path}"]
assert_equal args[1], `#{cmd}`.chomp assert_equal args[1], `#{cmd}`.chomp
end end
...@@ -73,11 +72,11 @@ class ThumbnailTest < Test::Unit::TestCase ...@@ -73,11 +72,11 @@ class ThumbnailTest < Test::Unit::TestCase
end end
context "being thumbnailed at 100x50 with cropping" do context "being thumbnailed at 100x50 with cropping" do
setup do before do
@thumb = Paperclip::Thumbnail.new(@file, :geometry => "100x50#") @thumb = Paperclip::Thumbnail.new(@file, :geometry => "100x50#")
end end
should "let us know when a command isn't found versus a processing error" do it "let us know when a command isn't found versus a processing error" do
old_path = ENV['PATH'] old_path = ENV['PATH']
begin begin
Cocaine::CommandLine.path = '' Cocaine::CommandLine.path = ''
...@@ -93,28 +92,28 @@ class ThumbnailTest < Test::Unit::TestCase ...@@ -93,28 +92,28 @@ class ThumbnailTest < Test::Unit::TestCase
end end
end end
should "report its correct current and target geometries" do it "report its correct current and target geometries" do
assert_equal "100x50#", @thumb.target_geometry.to_s assert_equal "100x50#", @thumb.target_geometry.to_s
assert_equal "434x66", @thumb.current_geometry.to_s assert_equal "434x66", @thumb.current_geometry.to_s
end end
should "report its correct format" do it "report its correct format" do
assert_nil @thumb.format assert_nil @thumb.format
end end
should "have whiny turned on by default" do it "have whiny turned on by default" do
assert @thumb.whiny assert @thumb.whiny
end end
should "have convert_options set to nil by default" do it "have convert_options set to nil by default" do
assert_equal nil, @thumb.convert_options assert_equal nil, @thumb.convert_options
end end
should "have source_file_options set to nil by default" do it "have source_file_options set to nil by default" do
assert_equal nil, @thumb.source_file_options assert_equal nil, @thumb.source_file_options
end end
should "send the right command to convert when sent #make" do it "send the right command to convert when sent #make" do
@thumb.expects(:convert).with do |*arg| @thumb.expects(:convert).with do |*arg|
arg[0] == ':source -auto-orient -resize "x50" -crop "100x50+114+0" +repage :dest' && arg[0] == ':source -auto-orient -resize "x50" -crop "100x50+114+0" +repage :dest' &&
arg[1][:source] == "#{File.expand_path(@thumb.file.path)}[0]" arg[1][:source] == "#{File.expand_path(@thumb.file.path)}[0]"
...@@ -122,13 +121,13 @@ class ThumbnailTest < Test::Unit::TestCase ...@@ -122,13 +121,13 @@ class ThumbnailTest < Test::Unit::TestCase
@thumb.make @thumb.make
end end
should "create the thumbnail when sent #make" do it "create the thumbnail when sent #make" do
dst = @thumb.make dst = @thumb.make
assert_match /100x50/, `identify "#{dst.path}"` assert_match /100x50/, `identify "#{dst.path}"`
end end
end end
should 'properly crop a EXIF-rotated image' do it 'properly crop a EXIF-rotated image' do
file = File.new(fixture_file('rotated.jpg')) file = File.new(fixture_file('rotated.jpg'))
thumb = Paperclip::Thumbnail.new(file, :geometry => "50x50#") thumb = Paperclip::Thumbnail.new(file, :geometry => "50x50#")
...@@ -139,17 +138,17 @@ class ThumbnailTest < Test::Unit::TestCase ...@@ -139,17 +138,17 @@ class ThumbnailTest < Test::Unit::TestCase
end end
context "being thumbnailed with source file options set" do context "being thumbnailed with source file options set" do
setup do before do
@thumb = Paperclip::Thumbnail.new(@file, @thumb = Paperclip::Thumbnail.new(@file,
:geometry => "100x50#", :geometry => "100x50#",
:source_file_options => "-strip") :source_file_options => "-strip")
end end
should "have source_file_options value set" do it "have source_file_options value set" do
assert_equal ["-strip"], @thumb.source_file_options assert_equal ["-strip"], @thumb.source_file_options
end end
should "send the right command to convert when sent #make" do it "send the right command to convert when sent #make" do
@thumb.expects(:convert).with do |*arg| @thumb.expects(:convert).with do |*arg|
arg[0] == '-strip :source -auto-orient -resize "x50" -crop "100x50+114+0" +repage :dest' && arg[0] == '-strip :source -auto-orient -resize "x50" -crop "100x50+114+0" +repage :dest' &&
arg[1][:source] == "#{File.expand_path(@thumb.file.path)}[0]" arg[1][:source] == "#{File.expand_path(@thumb.file.path)}[0]"
...@@ -157,19 +156,19 @@ class ThumbnailTest < Test::Unit::TestCase ...@@ -157,19 +156,19 @@ class ThumbnailTest < Test::Unit::TestCase
@thumb.make @thumb.make
end end
should "create the thumbnail when sent #make" do it "create the thumbnail when sent #make" do
dst = @thumb.make dst = @thumb.make
assert_match /100x50/, `identify "#{dst.path}"` assert_match /100x50/, `identify "#{dst.path}"`
end end
context "redefined to have bad source_file_options setting" do context "redefined to have bad source_file_options setting" do
setup do before do
@thumb = Paperclip::Thumbnail.new(@file, @thumb = Paperclip::Thumbnail.new(@file,
:geometry => "100x50#", :geometry => "100x50#",
:source_file_options => "-this-aint-no-option") :source_file_options => "-this-aint-no-option")
end end
should "error when trying to create the thumbnail" do it "error when trying to create the thumbnail" do
assert_raises(Paperclip::Error) do assert_raises(Paperclip::Error) do
silence_stream(STDERR) do silence_stream(STDERR) do
@thumb.make @thumb.make
...@@ -180,17 +179,17 @@ class ThumbnailTest < Test::Unit::TestCase ...@@ -180,17 +179,17 @@ class ThumbnailTest < Test::Unit::TestCase
end end
context "being thumbnailed with convert options set" do context "being thumbnailed with convert options set" do
setup do before do
@thumb = Paperclip::Thumbnail.new(@file, @thumb = Paperclip::Thumbnail.new(@file,
:geometry => "100x50#", :geometry => "100x50#",
:convert_options => "-strip -depth 8") :convert_options => "-strip -depth 8")
end end
should "have convert_options value set" do it "have convert_options value set" do
assert_equal %w"-strip -depth 8", @thumb.convert_options assert_equal %w"-strip -depth 8", @thumb.convert_options
end end
should "send the right command to convert when sent #make" do it "send the right command to convert when sent #make" do
@thumb.expects(:convert).with do |*arg| @thumb.expects(:convert).with do |*arg|
arg[0] == ':source -auto-orient -resize "x50" -crop "100x50+114+0" +repage -strip -depth 8 :dest' && arg[0] == ':source -auto-orient -resize "x50" -crop "100x50+114+0" +repage -strip -depth 8 :dest' &&
arg[1][:source] == "#{File.expand_path(@thumb.file.path)}[0]" arg[1][:source] == "#{File.expand_path(@thumb.file.path)}[0]"
...@@ -198,19 +197,19 @@ class ThumbnailTest < Test::Unit::TestCase ...@@ -198,19 +197,19 @@ class ThumbnailTest < Test::Unit::TestCase
@thumb.make @thumb.make
end end
should "create the thumbnail when sent #make" do it "create the thumbnail when sent #make" do
dst = @thumb.make dst = @thumb.make
assert_match /100x50/, `identify "#{dst.path}"` assert_match /100x50/, `identify "#{dst.path}"`
end end
context "redefined to have bad convert_options setting" do context "redefined to have bad convert_options setting" do
setup do before do
@thumb = Paperclip::Thumbnail.new(@file, @thumb = Paperclip::Thumbnail.new(@file,
:geometry => "100x50#", :geometry => "100x50#",
:convert_options => "-this-aint-no-option") :convert_options => "-this-aint-no-option")
end end
should "error when trying to create the thumbnail" do it "error when trying to create the thumbnail" do
assert_raises(Paperclip::Error) do assert_raises(Paperclip::Error) do
silence_stream(STDERR) do silence_stream(STDERR) do
@thumb.make @thumb.make
...@@ -218,7 +217,7 @@ class ThumbnailTest < Test::Unit::TestCase ...@@ -218,7 +217,7 @@ class ThumbnailTest < Test::Unit::TestCase
end end
end end
should "let us know when a command isn't found versus a processing error" do it "let us know when a command isn't found versus a processing error" do
old_path = ENV['PATH'] old_path = ENV['PATH']
begin begin
Cocaine::CommandLine.path = '' Cocaine::CommandLine.path = ''
...@@ -237,19 +236,19 @@ class ThumbnailTest < Test::Unit::TestCase ...@@ -237,19 +236,19 @@ class ThumbnailTest < Test::Unit::TestCase
end end
context "being thumbnailed with a blank geometry string" do context "being thumbnailed with a blank geometry string" do
setup do before do
@thumb = Paperclip::Thumbnail.new(@file, @thumb = Paperclip::Thumbnail.new(@file,
:geometry => "", :geometry => "",
:convert_options => "-gravity center -crop \"300x300+0-0\"") :convert_options => "-gravity center -crop \"300x300+0-0\"")
end end
should "not get resized by default" do it "not get resized by default" do
assert !@thumb.transformation_command.include?("-resize") assert !@thumb.transformation_command.include?("-resize")
end end
end end
context "being thumbnailed with default animated option (true)" do context "being thumbnailed with default animated option (true)" do
should "call identify to check for animated images when sent #make" do it "call identify to check for animated images when sent #make" do
thumb = Paperclip::Thumbnail.new(@file, :geometry => "100x50#") thumb = Paperclip::Thumbnail.new(@file, :geometry => "100x50#")
thumb.expects(:identify).at_least_once.with do |*arg| thumb.expects(:identify).at_least_once.with do |*arg|
arg[0] == '-format %m :file' && arg[0] == '-format %m :file' &&
...@@ -260,11 +259,11 @@ class ThumbnailTest < Test::Unit::TestCase ...@@ -260,11 +259,11 @@ class ThumbnailTest < Test::Unit::TestCase
end end
context "passing a custom file geometry parser" do context "passing a custom file geometry parser" do
teardown do after do
self.class.send(:remove_const, :GeoParser) Object.send(:remove_const, :GeoParser)
end end
should "produce the appropriate transformation_command" do it "produce the appropriate transformation_command" do
GeoParser = Class.new do GeoParser = Class.new do
def self.from_file(file) def self.from_file(file)
new new
...@@ -275,7 +274,7 @@ class ThumbnailTest < Test::Unit::TestCase ...@@ -275,7 +274,7 @@ class ThumbnailTest < Test::Unit::TestCase
end end
end end
thumb = Paperclip::Thumbnail.new(@file, :geometry => '50x50', :file_geometry_parser => GeoParser) thumb = Paperclip::Thumbnail.new(@file, :geometry => '50x50', :file_geometry_parser => ::GeoParser)
transformation_command = thumb.transformation_command transformation_command = thumb.transformation_command
...@@ -291,11 +290,11 @@ class ThumbnailTest < Test::Unit::TestCase ...@@ -291,11 +290,11 @@ class ThumbnailTest < Test::Unit::TestCase
end end
context "passing a custom geometry string parser" do context "passing a custom geometry string parser" do
teardown do after do
self.class.send(:remove_const, :GeoParser) Object.send(:remove_const, :GeoParser)
end end
should "produce the appropriate transformation_command" do it "produce the appropriate transformation_command" do
GeoParser = Class.new do GeoParser = Class.new do
def self.parse(s) def self.parse(s)
new new
...@@ -306,7 +305,7 @@ class ThumbnailTest < Test::Unit::TestCase ...@@ -306,7 +305,7 @@ class ThumbnailTest < Test::Unit::TestCase
end end
end end
thumb = Paperclip::Thumbnail.new(@file, :geometry => '50x50', :string_geometry_parser => GeoParser) thumb = Paperclip::Thumbnail.new(@file, :geometry => '50x50', :string_geometry_parser => ::GeoParser)
transformation_command = thumb.transformation_command transformation_command = thumb.transformation_command
...@@ -317,32 +316,32 @@ class ThumbnailTest < Test::Unit::TestCase ...@@ -317,32 +316,32 @@ class ThumbnailTest < Test::Unit::TestCase
end end
context "A multipage PDF" do context "A multipage PDF" do
setup do before do
@file = File.new(fixture_file("twopage.pdf"), 'rb') @file = File.new(fixture_file("twopage.pdf"), 'rb')
end end
teardown { @file.close } after { @file.close }
should "start with two pages with dimensions 612x792" do it "start with two pages with dimensions 612x792" do
cmd = %Q[identify -format "%wx%h" "#{@file.path}"] cmd = %Q[identify -format "%wx%h" "#{@file.path}"]
assert_equal "612x792"*2, `#{cmd}`.chomp assert_equal "612x792"*2, `#{cmd}`.chomp
end end
context "being thumbnailed at 100x100 with cropping" do context "being thumbnailed at 100x100 with cropping" do
setup do before do
@thumb = Paperclip::Thumbnail.new(@file, :geometry => "100x100#", :format => :png) @thumb = Paperclip::Thumbnail.new(@file, :geometry => "100x100#", :format => :png)
end end
should "report its correct current and target geometries" do it "report its correct current and target geometries" do
assert_equal "100x100#", @thumb.target_geometry.to_s assert_equal "100x100#", @thumb.target_geometry.to_s
assert_equal "612x792", @thumb.current_geometry.to_s assert_equal "612x792", @thumb.current_geometry.to_s
end end
should "report its correct format" do it "report its correct format" do
assert_equal :png, @thumb.format assert_equal :png, @thumb.format
end end
should "create the thumbnail when sent #make" do it "create the thumbnail when sent #make" do
dst = @thumb.make dst = @thumb.make
assert_match /100x100/, `identify "#{dst.path}"` assert_match /100x100/, `identify "#{dst.path}"`
end end
...@@ -350,23 +349,23 @@ class ThumbnailTest < Test::Unit::TestCase ...@@ -350,23 +349,23 @@ class ThumbnailTest < Test::Unit::TestCase
end end
context "An animated gif" do context "An animated gif" do
setup do before do
@file = File.new(fixture_file("animated.gif"), 'rb') @file = File.new(fixture_file("animated.gif"), 'rb')
end end
teardown { @file.close } after { @file.close }
should "start with 12 frames with size 100x100" do it "start with 12 frames with size 100x100" do
cmd = %Q[identify -format "%wx%h" "#{@file.path}"] cmd = %Q[identify -format "%wx%h" "#{@file.path}"]
assert_equal "100x100"*12, `#{cmd}`.chomp assert_equal "100x100"*12, `#{cmd}`.chomp
end end
context "with static output" do context "with static output" do
setup do before do
@thumb = Paperclip::Thumbnail.new(@file, :geometry => "50x50", :format => :jpg) @thumb = Paperclip::Thumbnail.new(@file, :geometry => "50x50", :format => :jpg)
end end
should "create the single frame thumbnail when sent #make" do it "create the single frame thumbnail when sent #make" do
dst = @thumb.make dst = @thumb.make
cmd = %Q[identify -format "%wx%h" "#{dst.path}"] cmd = %Q[identify -format "%wx%h" "#{dst.path}"]
assert_equal "50x50", `#{cmd}`.chomp assert_equal "50x50", `#{cmd}`.chomp
...@@ -374,11 +373,11 @@ class ThumbnailTest < Test::Unit::TestCase ...@@ -374,11 +373,11 @@ class ThumbnailTest < Test::Unit::TestCase
end end
context "with animated output format" do context "with animated output format" do
setup do before do
@thumb = Paperclip::Thumbnail.new(@file, :geometry => "50x50", :format => :gif) @thumb = Paperclip::Thumbnail.new(@file, :geometry => "50x50", :format => :gif)
end end
should "create the 12 frames thumbnail when sent #make" do it "create the 12 frames thumbnail when sent #make" do
dst = @thumb.make dst = @thumb.make
cmd = %Q[identify -format "%wx%h," "#{dst.path}"] cmd = %Q[identify -format "%wx%h," "#{dst.path}"]
frames = `#{cmd}`.chomp.split(',') frames = `#{cmd}`.chomp.split(',')
...@@ -386,21 +385,21 @@ class ThumbnailTest < Test::Unit::TestCase ...@@ -386,21 +385,21 @@ class ThumbnailTest < Test::Unit::TestCase
assert_frame_dimensions (45..50), frames assert_frame_dimensions (45..50), frames
end end
should "use the -coalesce option" do it "use the -coalesce option" do
assert_equal @thumb.transformation_command.first, "-coalesce" assert_equal @thumb.transformation_command.first, "-coalesce"
end end
should "use the -layers 'optimize' option" do it "use the -layers 'optimize' option" do
assert_equal @thumb.transformation_command.last, '-layers "optimize"' assert_equal @thumb.transformation_command.last, '-layers "optimize"'
end end
end end
context "with omitted output format" do context "with omitted output format" do
setup do before do
@thumb = Paperclip::Thumbnail.new(@file, :geometry => "50x50") @thumb = Paperclip::Thumbnail.new(@file, :geometry => "50x50")
end end
should "create the 12 frames thumbnail when sent #make" do it "create the 12 frames thumbnail when sent #make" do
dst = @thumb.make dst = @thumb.make
cmd = %Q[identify -format "%wx%h," "#{dst.path}"] cmd = %Q[identify -format "%wx%h," "#{dst.path}"]
frames = `#{cmd}`.chomp.split(',') frames = `#{cmd}`.chomp.split(',')
...@@ -408,22 +407,22 @@ class ThumbnailTest < Test::Unit::TestCase ...@@ -408,22 +407,22 @@ class ThumbnailTest < Test::Unit::TestCase
assert_frame_dimensions (45..50), frames assert_frame_dimensions (45..50), frames
end end
should "use the -coalesce option" do it "use the -coalesce option" do
assert_equal @thumb.transformation_command.first, "-coalesce" assert_equal @thumb.transformation_command.first, "-coalesce"
end end
should "use the -layers 'optimize' option" do it "use the -layers 'optimize' option" do
assert_equal @thumb.transformation_command.last, '-layers "optimize"' assert_equal @thumb.transformation_command.last, '-layers "optimize"'
end end
end end
context "with unidentified source format" do context "with unidentified source format" do
setup do before do
@unidentified_file = File.new(fixture_file("animated.unknown"), 'rb') @unidentified_file = File.new(fixture_file("animated.unknown"), 'rb')
@thumb = Paperclip::Thumbnail.new(@file, :geometry => "60x60") @thumb = Paperclip::Thumbnail.new(@file, :geometry => "60x60")
end end
should "create the 12 frames thumbnail when sent #make" do it "create the 12 frames thumbnail when sent #make" do
dst = @thumb.make dst = @thumb.make
cmd = %Q[identify -format "%wx%h," "#{dst.path}"] cmd = %Q[identify -format "%wx%h," "#{dst.path}"]
frames = `#{cmd}`.chomp.split(',') frames = `#{cmd}`.chomp.split(',')
...@@ -431,22 +430,22 @@ class ThumbnailTest < Test::Unit::TestCase ...@@ -431,22 +430,22 @@ class ThumbnailTest < Test::Unit::TestCase
assert_frame_dimensions (55..60), frames assert_frame_dimensions (55..60), frames
end end
should "use the -coalesce option" do it "use the -coalesce option" do
assert_equal @thumb.transformation_command.first, "-coalesce" assert_equal @thumb.transformation_command.first, "-coalesce"
end end
should "use the -layers 'optimize' option" do it "use the -layers 'optimize' option" do
assert_equal @thumb.transformation_command.last, '-layers "optimize"' assert_equal @thumb.transformation_command.last, '-layers "optimize"'
end end
end end
context "with no source format" do context "with no source format" do
setup do before do
@unidentified_file = File.new(fixture_file("animated"), 'rb') @unidentified_file = File.new(fixture_file("animated"), 'rb')
@thumb = Paperclip::Thumbnail.new(@file, :geometry => "70x70") @thumb = Paperclip::Thumbnail.new(@file, :geometry => "70x70")
end end
should "create the 12 frames thumbnail when sent #make" do it "create the 12 frames thumbnail when sent #make" do
dst = @thumb.make dst = @thumb.make
cmd = %Q[identify -format "%wx%h," "#{dst.path}"] cmd = %Q[identify -format "%wx%h," "#{dst.path}"]
frames = `#{cmd}`.chomp.split(',') frames = `#{cmd}`.chomp.split(',')
...@@ -454,27 +453,27 @@ class ThumbnailTest < Test::Unit::TestCase ...@@ -454,27 +453,27 @@ class ThumbnailTest < Test::Unit::TestCase
assert_frame_dimensions (60..70), frames assert_frame_dimensions (60..70), frames
end end
should "use the -coalesce option" do it "use the -coalesce option" do
assert_equal @thumb.transformation_command.first, "-coalesce" assert_equal @thumb.transformation_command.first, "-coalesce"
end end
should "use the -layers 'optimize' option" do it "use the -layers 'optimize' option" do
assert_equal @thumb.transformation_command.last, '-layers "optimize"' assert_equal @thumb.transformation_command.last, '-layers "optimize"'
end end
end end
context "with animated option set to false" do context "with animated option set to false" do
setup do before do
@thumb = Paperclip::Thumbnail.new(@file, :geometry => "50x50", :animated => false) @thumb = Paperclip::Thumbnail.new(@file, :geometry => "50x50", :animated => false)
end end
should "output the gif format" do it "output the gif format" do
dst = @thumb.make dst = @thumb.make
cmd = %Q[identify "#{dst.path}"] cmd = %Q[identify "#{dst.path}"]
assert_match /GIF/, `#{cmd}`.chomp assert_match /GIF/, `#{cmd}`.chomp
end end
should "create the single frame thumbnail when sent #make" do it "create the single frame thumbnail when sent #make" do
dst = @thumb.make dst = @thumb.make
cmd = %Q[identify -format "%wx%h" "#{dst.path}"] cmd = %Q[identify -format "%wx%h" "#{dst.path}"]
assert_equal "50x50", `#{cmd}`.chomp assert_equal "50x50", `#{cmd}`.chomp
......
# 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 AttachmentContentTypeValidatorTest < Test::Unit::TestCase describe Paperclip::Validators::AttachmentContentTypeValidator 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,69 +13,68 @@ class AttachmentContentTypeValidatorTest < Test::Unit::TestCase ...@@ -14,69 +13,68 @@ class AttachmentContentTypeValidatorTest < Test::Unit::TestCase
end end
context "with a nil content type" do context "with a nil content type" do
setup do before do
build_validator :content_type => "image/jpg" build_validator :content_type => "image/jpg"
@dummy.stubs(:avatar_content_type => nil) @dummy.stubs(:avatar_content_type => nil)
@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_content_type].blank? assert @dummy.errors[:avatar_content_type].blank?
end end
end end
context "with :allow_nil option" do context "with :allow_nil option" do
context "as true" do context "as true" do
setup do before do
build_validator :content_type => "image/png", :allow_nil => true build_validator :content_type => "image/png", :allow_nil => true
@dummy.stubs(:avatar_content_type => nil) @dummy.stubs(:avatar_content_type => nil)
@validator.validate(@dummy) @validator.validate(@dummy)
end end
should "allow avatar_content_type as nil" do it "allow avatar_content_type as nil" do
assert @dummy.errors[:avatar_content_type].blank? assert @dummy.errors[:avatar_content_type].blank?
end end
end end
context "as false" do context "as false" do
setup do before do
build_validator :content_type => "image/png", :allow_nil => false build_validator :content_type => "image/png", :allow_nil => false
@dummy.stubs(:avatar_content_type => nil) @dummy.stubs(:avatar_content_type => nil)
@validator.validate(@dummy) @validator.validate(@dummy)
end end
should "not allow avatar_content_type as nil" do it "not allow avatar_content_type as nil" do
assert @dummy.errors[:avatar_content_type].present? assert @dummy.errors[:avatar_content_type].present?
end end
end end
end end
context "with a failing validation" do context "with a failing validation" do
setup do before do
build_validator :content_type => "image/png", :allow_nil => false build_validator :content_type => "image/png", :allow_nil => false
@dummy.stubs(:avatar_content_type => nil) @dummy.stubs(:avatar_content_type => nil)
@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
context "with a successful validation" do context "with a successful validation" do
setup do before do
build_validator :content_type => "image/png", :allow_nil => false build_validator :content_type => "image/png", :allow_nil => false
@dummy.stubs(:avatar_content_type => "image/png") @dummy.stubs(:avatar_content_type => "image/png")
@validator.validate(@dummy) @validator.validate(@dummy)
end end
should "not add error to the base object" do it "not add error to the base object" do
assert @dummy.errors[:avatar].blank?, assert @dummy.errors[:avatar].blank?,
"Error was added to base attribute" "Error was added to base attribute"
end end
...@@ -84,25 +82,25 @@ class AttachmentContentTypeValidatorTest < Test::Unit::TestCase ...@@ -84,25 +82,25 @@ class AttachmentContentTypeValidatorTest < Test::Unit::TestCase
context "with :allow_blank option" do context "with :allow_blank option" do
context "as true" do context "as true" do
setup do before do
build_validator :content_type => "image/png", :allow_blank => true build_validator :content_type => "image/png", :allow_blank => true
@dummy.stubs(:avatar_content_type => "") @dummy.stubs(:avatar_content_type => "")
@validator.validate(@dummy) @validator.validate(@dummy)
end end
should "allow avatar_content_type as blank" do it "allow avatar_content_type as blank" do
assert @dummy.errors[:avatar_content_type].blank? assert @dummy.errors[:avatar_content_type].blank?
end end
end end
context "as false" do context "as false" do
setup do before do
build_validator :content_type => "image/png", :allow_blank => false build_validator :content_type => "image/png", :allow_blank => false
@dummy.stubs(:avatar_content_type => "") @dummy.stubs(:avatar_content_type => "")
@validator.validate(@dummy) @validator.validate(@dummy)
end end
should "not allow avatar_content_type as blank" do it "not allow avatar_content_type as blank" do
assert @dummy.errors[:avatar_content_type].present? assert @dummy.errors[:avatar_content_type].present?
end end
end end
...@@ -111,37 +109,37 @@ class AttachmentContentTypeValidatorTest < Test::Unit::TestCase ...@@ -111,37 +109,37 @@ class AttachmentContentTypeValidatorTest < 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 string" do context "as a string" do
setup do before do
build_validator :content_type => "image/jpg" build_validator :content_type => "image/jpg"
@dummy.stubs(:avatar_content_type => "image/jpg") @dummy.stubs(:avatar_content_type => "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_content_type].blank? assert @dummy.errors[:avatar_content_type].blank?
end end
end end
context "as an regexp" do context "as an regexp" do
setup do before do
build_validator :content_type => /^image\/.*/ build_validator :content_type => /^image\/.*/
@dummy.stubs(:avatar_content_type => "image/jpg") @dummy.stubs(:avatar_content_type => "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_content_type].blank? assert @dummy.errors[:avatar_content_type].blank?
end end
end end
context "as a list" do context "as a list" do
setup do before do
build_validator :content_type => ["image/png", "image/jpg", "image/jpeg"] build_validator :content_type => ["image/png", "image/jpg", "image/jpeg"]
@dummy.stubs(:avatar_content_type => "image/jpg") @dummy.stubs(:avatar_content_type => "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_content_type].blank? assert @dummy.errors[:avatar_content_type].blank?
end end
end end
...@@ -149,53 +147,53 @@ class AttachmentContentTypeValidatorTest < Test::Unit::TestCase ...@@ -149,53 +147,53 @@ class AttachmentContentTypeValidatorTest < Test::Unit::TestCase
context "with a disallowed type" do context "with a disallowed type" do
context "as a string" do context "as a string" do
setup do before do
build_validator :content_type => "image/png" build_validator :content_type => "image/png"
@dummy.stubs(:avatar_content_type => "image/jpg") @dummy.stubs(:avatar_content_type => "image/jpg")
@validator.validate(@dummy) @validator.validate(@dummy)
end end
should "set a correct default error message" do it "set a correct default error message" do
assert @dummy.errors[:avatar_content_type].present? assert @dummy.errors[:avatar_content_type].present?
assert_includes @dummy.errors[:avatar_content_type], "is invalid" expect(@dummy.errors[:avatar_content_type]).to include "is invalid"
end end
end end
context "as a regexp" do context "as a regexp" do
setup do before do
build_validator :content_type => /^text\/.*/ build_validator :content_type => /^text\/.*/
@dummy.stubs(:avatar_content_type => "image/jpg") @dummy.stubs(:avatar_content_type => "image/jpg")
@validator.validate(@dummy) @validator.validate(@dummy)
end end
should "set a correct default error message" do it "set a correct default error message" do
assert @dummy.errors[:avatar_content_type].present? assert @dummy.errors[:avatar_content_type].present?
assert_includes @dummy.errors[:avatar_content_type], "is invalid" expect(@dummy.errors[:avatar_content_type]).to include "is invalid"
end end
end end
context "with :message option" do context "with :message option" do
context "without interpolation" do context "without interpolation" do
setup do before do
build_validator :content_type => "image/png", :message => "should be a PNG image" build_validator :content_type => "image/png", :message => "should be a PNG image"
@dummy.stubs(:avatar_content_type => "image/jpg") @dummy.stubs(:avatar_content_type => "image/jpg")
@validator.validate(@dummy) @validator.validate(@dummy)
end end
should "set a correct error message" do it "set a correct error message" do
assert_includes @dummy.errors[:avatar_content_type], "should be a PNG image" expect(@dummy.errors[:avatar_content_type]).to include "should be a PNG image"
end end
end end
context "with interpolation" do context "with interpolation" do
setup do before do
build_validator :content_type => "image/png", :message => "should have content type %{types}" build_validator :content_type => "image/png", :message => "should have content type %{types}"
@dummy.stubs(:avatar_content_type => "image/jpg") @dummy.stubs(:avatar_content_type => "image/jpg")
@validator.validate(@dummy) @validator.validate(@dummy)
end end
should "set a correct error message" do it "set a correct error message" do
assert_includes @dummy.errors[:avatar_content_type], "should have content type image/png" expect(@dummy.errors[:avatar_content_type]).to include "should have content type image/png"
end end
end end
end end
...@@ -205,37 +203,37 @@ class AttachmentContentTypeValidatorTest < Test::Unit::TestCase ...@@ -205,37 +203,37 @@ class AttachmentContentTypeValidatorTest < 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 string" do context "as a string" do
setup do before do
build_validator :not => "image/gif" build_validator :not => "image/gif"
@dummy.stubs(:avatar_content_type => "image/jpg") @dummy.stubs(:avatar_content_type => "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_content_type].blank? assert @dummy.errors[:avatar_content_type].blank?
end end
end end
context "as an regexp" do context "as an regexp" do
setup do before do
build_validator :not => /^text\/.*/ build_validator :not => /^text\/.*/
@dummy.stubs(:avatar_content_type => "image/jpg") @dummy.stubs(:avatar_content_type => "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_content_type].blank? assert @dummy.errors[:avatar_content_type].blank?
end end
end end
context "as a list" do context "as a list" do
setup do before do
build_validator :not => ["image/png", "image/jpg", "image/jpeg"] build_validator :not => ["image/png", "image/jpg", "image/jpeg"]
@dummy.stubs(:avatar_content_type => "image/gif") @dummy.stubs(:avatar_content_type => "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_content_type].blank? assert @dummy.errors[:avatar_content_type].blank?
end end
end end
...@@ -243,53 +241,53 @@ class AttachmentContentTypeValidatorTest < Test::Unit::TestCase ...@@ -243,53 +241,53 @@ class AttachmentContentTypeValidatorTest < Test::Unit::TestCase
context "with a disallowed type" do context "with a disallowed type" do
context "as a string" do context "as a string" do
setup do before do
build_validator :not => "image/png" build_validator :not => "image/png"
@dummy.stubs(:avatar_content_type => "image/png") @dummy.stubs(:avatar_content_type => "image/png")
@validator.validate(@dummy) @validator.validate(@dummy)
end end
should "set a correct default error message" do it "set a correct default error message" do
assert @dummy.errors[:avatar_content_type].present? assert @dummy.errors[:avatar_content_type].present?
assert_includes @dummy.errors[:avatar_content_type], "is invalid" expect(@dummy.errors[:avatar_content_type]).to include "is invalid"
end end
end end
context "as a regexp" do context "as a regexp" do
setup do before do
build_validator :not => /^text\/.*/ build_validator :not => /^text\/.*/
@dummy.stubs(:avatar_content_type => "text/plain") @dummy.stubs(:avatar_content_type => "text/plain")
@validator.validate(@dummy) @validator.validate(@dummy)
end end
should "set a correct default error message" do it "set a correct default error message" do
assert @dummy.errors[:avatar_content_type].present? assert @dummy.errors[:avatar_content_type].present?
assert_includes @dummy.errors[:avatar_content_type], "is invalid" expect(@dummy.errors[:avatar_content_type]).to include "is invalid"
end end
end end
context "with :message option" do context "with :message option" do
context "without interpolation" do context "without interpolation" do
setup do before do
build_validator :not => "image/png", :message => "should not be a PNG image" build_validator :not => "image/png", :message => "should not be a PNG image"
@dummy.stubs(:avatar_content_type => "image/png") @dummy.stubs(:avatar_content_type => "image/png")
@validator.validate(@dummy) @validator.validate(@dummy)
end end
should "set a correct error message" do it "set a correct error message" do
assert_includes @dummy.errors[:avatar_content_type], "should not be a PNG image" expect(@dummy.errors[:avatar_content_type]).to include "should not be a PNG image"
end end
end end
context "with interpolation" do context "with interpolation" do
setup do before do
build_validator :not => "image/png", :message => "should not have content type %{types}" build_validator :not => "image/png", :message => "should not have content type %{types}"
@dummy.stubs(:avatar_content_type => "image/png") @dummy.stubs(:avatar_content_type => "image/png")
@validator.validate(@dummy) @validator.validate(@dummy)
end end
should "set a correct error message" do it "set a correct error message" do
assert_includes @dummy.errors[:avatar_content_type], "should not have content type image/png" expect(@dummy.errors[:avatar_content_type]).to include "should not have content type image/png"
end end
end end
end end
...@@ -297,27 +295,27 @@ class AttachmentContentTypeValidatorTest < Test::Unit::TestCase ...@@ -297,27 +295,27 @@ class AttachmentContentTypeValidatorTest < Test::Unit::TestCase
end end
context "using the helper" do context "using the helper" do
setup do before do
Dummy.validates_attachment_content_type :avatar, :content_type => "image/jpg" Dummy.validates_attachment_content_type :avatar, :content_type => "image/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_content_type } assert Dummy.validators_on(:avatar).any?{ |validator| validator.kind == :attachment_content_type }
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 :content_type was given" do it "not raise argument error if :content_type was given" do
build_validator :content_type => "image/jpg" build_validator :content_type => "image/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 => "image/jpg" build_validator :not => "image/jpg"
end end
end end
......
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