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
*.log
test/s3.yml
test/paperclip.db
test/doc
test/pkg
test/tmp
public
paperclip*.gem
capybara*.html
......
......@@ -3,13 +3,13 @@ rvm:
- jruby-19mode
- rbx
- 2.0.0
- 2.1.0
- 2.1.1
install:
- "travis_retry bundle install"
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:
- gemfiles/3.2.gemfile
......@@ -21,3 +21,4 @@ matrix:
allow_failures:
- rvm: jruby-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
gem "rails", "~> 3.2.15"
gem "paperclip", :path => "../"
......
......@@ -17,8 +17,9 @@ a test!
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
accept, pull requests within three business days (and, typically, one business
day). We may suggest some changes or improvements or alternatives.
accept, pull requests within seven business days (most of the work on Paperclip
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,
taken straight from the Ruby on Rails guide:
......@@ -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
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:
bundle install
......@@ -47,15 +52,15 @@ version of Rails, which defined in `gemfiles/*.gemfile`.
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
You need to specify a `BUNDLE_GEMFILE` pointing to the gemfile before running
the normal test command:
BUNDLE_GEMFILE=gemfiles/3.2.gemfile ruby -Itest test/schema_test.rb
BUNDLE_GEMFILE=gemfiles/3.2.gemfile cucumber features/basic_integration.feature
BUNDLE_GEMFILE=gemfiles/4.1.gemfile rspec spec/paperclip/attachment_spec.rb
BUNDLE_GEMFILE=gemfiles/4.1.gemfile cucumber features/basic_integration.feature
Syntax
------
......
......@@ -2,12 +2,9 @@ source "https://rubygems.org"
gemspec
gem 'sqlite3', '~> 1.3.4', :platform => :ruby
gem 'jruby-openssl', :platform => :jruby
gem 'activerecord-jdbcsqlite3-adapter', :platform => :jruby
gem 'pry', :platform => :ruby
gem 'pry-byebug', :platform => :ruby
gem 'rubysl', :platform => :rbx
# Hinting at development dependencies
......
require 'bundler/gem_tasks'
require 'appraisal'
require 'rake/testtask'
require 'rspec/core/rake_task'
require 'cucumber/rake/task'
desc 'Default: run unit tests.'
......@@ -9,19 +9,15 @@ task :default => [:clean, :all]
desc 'Test the paperclip plugin under all supported Rails versions.'
task :all do |t|
if ENV['BUNDLE_GEMFILE']
exec('rake test cucumber')
exec('rake spec cucumber')
else
Rake::Task["appraisal:install"].execute
exec('rake appraisal test cucumber')
exec('rake appraisal spec cucumber')
end
end
desc 'Test the paperclip plugin.'
Rake::TestTask.new(:test) do |t|
t.libs << 'lib' << 'profile'
t.pattern = 'test/**/*_test.rb'
t.verbose = true
end
RSpec::Core::RakeTask.new(:spec)
desc 'Run integration test'
Cucumber::Rake::Task.new do |t|
......
......@@ -18,11 +18,11 @@ Feature: Rails integration
And I start the rails application
When I go to the new user page
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"
Then I should see "Name: something"
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
Given I attach :attachment with:
......@@ -32,11 +32,11 @@ Feature: Rails integration
And I start the rails application
When I go to the new user page
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"
Then I should see "Name: something"
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
Given I attach :attachment with:
......@@ -55,7 +55,7 @@ Feature: Rails integration
And I start the rails application
When I go to the new user page
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"
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"
......
module AttachmentHelpers
def fixture_path(filename)
File.expand_path("#{PROJECT_ROOT}/test/fixtures/#{filename}")
File.expand_path("#{PROJECT_ROOT}/spec/fixtures/#{filename}")
end
def attachment_path(filename)
......
require 'aruba/cucumber'
require 'capybara/cucumber'
require 'test/unit/assertions'
require 'rspec/matchers'
$CUCUMBER=1
World(Test::Unit::Assertions)
World(RSpec::Matchers)
Before do
@aruba_timeout_seconds = 120
......
......@@ -2,9 +2,10 @@
source "https://rubygems.org"
gem "sqlite3", "~> 1.3.4", :platform=>:ruby
gem "jruby-openssl", :platform=>:jruby
gem "activerecord-jdbcsqlite3-adapter", :platform=>:jruby
gem "pry", :platform=>:ruby
gem "rubysl", :platform=>:rbx
gem "rails", "~> 3.2.15"
gem "paperclip", :path=>"../"
......
......@@ -2,9 +2,10 @@
source "https://rubygems.org"
gem "sqlite3", "~> 1.3.4", :platform=>:ruby
gem "jruby-openssl", :platform=>:jruby
gem "activerecord-jdbcsqlite3-adapter", :platform=>:jruby
gem "pry", :platform=>:ruby
gem "rubysl", :platform=>:rbx
gem "rails", "~> 4.0.0"
gem "paperclip", :path=>"../"
......
......@@ -2,10 +2,11 @@
source "https://rubygems.org"
gem "sqlite3", "~> 1.3.4", :platform=>:ruby
gem "jruby-openssl", :platform=>:jruby
gem "activerecord-jdbcsqlite3-adapter", :platform=>:jruby
gem "sqlite3", :platform=>:ruby
gem "rubysl", :platform=>:rbx
gem "rails", "~> 4.1.0.beta"
gem "paperclip", :path=>"../"
gemspec :path=>"../"
gemspec :path=>"../"
\ No newline at end of file
......@@ -16,8 +16,6 @@ class PaperclipGenerator < ActiveRecord::Generators::Base
migration_template "paperclip_migration.rb.erb", "db/migrate/#{migration_file_name}"
end
protected
def migration_name
"add_attachment_#{attachment_names.join("_")}_to_#{name.underscore.pluralize}"
end
......
......@@ -15,7 +15,7 @@ Gem::Specification.new do |s|
s.rubyforge_project = "paperclip"
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.require_paths = ["lib"]
......@@ -29,12 +29,12 @@ Gem::Specification.new do |s|
s.add_development_dependency('activerecord', '>= 3.0.0')
s.add_development_dependency('shoulda')
s.add_development_dependency('rspec')
s.add_development_dependency('appraisal')
s.add_development_dependency('mocha')
s.add_development_dependency('aws-sdk', '>= 1.5.7')
s.add_development_dependency('bourne')
s.add_development_dependency('sqlite3', '~> 1.3.4')
s.add_development_dependency('cucumber', '~> 1.2.1')
s.add_development_dependency('cucumber', '~> 1.3.11')
s.add_development_dependency('aruba')
s.add_development_dependency('nokogiri')
# Ruby version < 1.9.3 can't install capybara > 2.0.3.
......@@ -46,4 +46,5 @@ Gem::Specification.new do |s|
s.add_development_dependency('fakeweb')
s.add_development_dependency('railties')
s.add_development_dependency('actionmailer', '>= 3.0.0')
s.add_development_dependency('generator_spec')
end
......@@ -132,4 +132,3 @@ elsif defined?(Test)
extend Paperclip::Shoulda
end
end
require './test/helper'
require 'spec_helper'
class AttachmentDefinitionsTest < Test::Unit::TestCase
should 'return all of the attachments on the class' do
describe "Attachment Definitions" do
it 'returns all of the attachments on the class' do
reset_class "Dummy"
Dummy.has_attached_file :avatar, {:path => "abc"}
Dummy.has_attached_file :other_attachment, {:url => "123"}
......
# encoding: utf-8
require './test/helper'
require 'paperclip/attachment'
class AttachmentProcessingTest < Test::Unit::TestCase
def setup
rebuild_model
end
require 'spec_helper'
describe 'Attachment Processing' do
context 'using validates_attachment_content_type' do
should 'process attachments given a valid assignment' do
before do
rebuild_class
end
it 'process attachments given a valid assignment' do
file = File.new(fixture_file("5k.png"))
Dummy.validates_attachment_content_type :avatar, :content_type => "image/png"
instance = Dummy.new
......@@ -18,7 +17,7 @@ class AttachmentProcessingTest < Test::Unit::TestCase
attachment.assign(file)
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"))
Dummy.validates_attachment_content_type :avatar, :not => "image/png"
instance = Dummy.new
......@@ -28,7 +27,7 @@ class AttachmentProcessingTest < Test::Unit::TestCase
attachment.assign(file)
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"))
Dummy.validates_attachment_content_type :avatar, :content_type => "image/tiff"
instance = Dummy.new
......@@ -38,7 +37,7 @@ class AttachmentProcessingTest < Test::Unit::TestCase
attachment.assign(file)
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"))
Dummy.validates_attachment_content_type :avatar, :content_type => "image/tiff", :if => lambda{false}
instance = Dummy.new
......@@ -50,7 +49,7 @@ class AttachmentProcessingTest < Test::Unit::TestCase
end
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"))
Dummy.validates_attachment :avatar, :content_type => {:content_type => "image/png"}
instance = Dummy.new
......@@ -60,7 +59,7 @@ class AttachmentProcessingTest < Test::Unit::TestCase
attachment.assign(file)
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"))
Dummy.validates_attachment :avatar, :content_type => {:not => "image/png"}
instance = Dummy.new
......@@ -70,7 +69,7 @@ class AttachmentProcessingTest < Test::Unit::TestCase
attachment.assign(file)
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"))
Dummy.validates_attachment :avatar, :content_type => {:content_type => "image/tiff"}
instance = Dummy.new
......
require './test/helper'
require 'paperclip/attachment_registry'
require 'spec_helper'
class AttachmentRegistryTest < Test::Unit::TestCase
def setup
describe 'Attachment Registry' do
before do
Paperclip::AttachmentRegistry.clear
end
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
Paperclip::AttachmentRegistry.register(foo, :avatar, {})
assert_equal [:avatar], Paperclip::AttachmentRegistry.names_for(foo)
end
should 'not include attachment names for other classes' do
it 'not include attachment names for other classes' do
foo = Class.new
bar = Class.new
Paperclip::AttachmentRegistry.register(foo, :avatar, {})
......@@ -23,13 +22,13 @@ class AttachmentRegistryTest < Test::Unit::TestCase
assert_equal [:lover], Paperclip::AttachmentRegistry.names_for(bar)
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)
end
end
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
expected_accumulations = [
[foo, :avatar, { yo: 'greeting' }],
......@@ -49,7 +48,7 @@ class AttachmentRegistryTest < Test::Unit::TestCase
end
context '.definitions_for' do
should 'produce the attachment name and options' do
it 'produce the attachment name and options' do
expected_definitions = {
avatar: { yo: 'greeting' },
greeter: { ciao: 'greeting' }
......@@ -63,7 +62,7 @@ class AttachmentRegistryTest < Test::Unit::TestCase
assert_equal expected_definitions, definitions
end
should "produce defintions for subclasses" do
it "produce defintions for subclasses" do
expected_definitions = { avatar: { yo: 'greeting' } }
Foo = Class.new
Bar = Class.new(Foo)
......@@ -76,7 +75,7 @@ class AttachmentRegistryTest < Test::Unit::TestCase
end
context '.clear' do
should 'remove all of the existing attachment definitions' do
it 'remove all of the existing attachment definitions' do
foo = Class.new
Paperclip::AttachmentRegistry.register(foo, :greeter, { ciao: 'greeting' })
......
# encoding: utf-8
require './test/helper'
require 'paperclip/attachment'
require 'spec_helper'
class Dummy; end
describe Paperclip::Attachment do
class AttachmentTest < Test::Unit::TestCase
context "presence" do
setup do
rebuild_class
@dummy = Dummy.new
end
context "when file not set" do
should "not be present" do
assert @dummy.avatar.blank?
refute @dummy.avatar.present?
end
end
context "when file set" do
setup { @dummy.avatar = File.new(fixture_file("50x50.png"), "rb") }
it "is not present when file not set" do
rebuild_class
dummy = Dummy.new
expect(dummy.avatar).to be_blank
expect(dummy.avatar).to_not be_present
end
should "be present" do
refute @dummy.avatar.blank?
assert @dummy.avatar.present?
end
end
it "is present when the file is set" do
rebuild_class
dummy = Dummy.new
dummy.avatar = File.new(fixture_file("50x50.png"), "rb")
expect(dummy.avatar).to_not be_blank
expect(dummy.avatar).to be_present
end
should "process :original style first" do
it "processes :original style first" do
file = File.new(fixture_file("50x50.png"), 'rb')
rebuild_class :styles => { :small => '100x>', :original => '42x42#' }
dummy = Dummy.new
......@@ -37,12 +26,12 @@ class AttachmentTest < Test::Unit::TestCase
dummy.save
# :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
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')
rebuild_class :styles => { :small => '100x>',
:large => '500x>',
......@@ -51,57 +40,56 @@ class AttachmentTest < Test::Unit::TestCase
dummy.avatar = file
dummy.save
assert_file_exists(dummy.avatar.path(:small))
assert_file_exists(dummy.avatar.path(:large))
assert_file_exists(dummy.avatar.path(:original))
expect(dummy.avatar.path(:small)).to exist
expect(dummy.avatar.path(:large)).to exist
expect(dummy.avatar.path(:original)).to exist
dummy.avatar.reprocess!(:small)
assert_file_exists(dummy.avatar.path(:small))
assert_file_exists(dummy.avatar.path(:large))
assert_file_exists(dummy.avatar.path(:original))
expect(dummy.avatar.path(:small)).to exist
expect(dummy.avatar.path(:large)).to exist
expect(dummy.avatar.path(:original)).to exist
end
context "having a not empty hash as a default option" do
setup do
before do
@old_default_options = Paperclip::Attachment.default_options.dup
@new_default_options = { :convert_options => { :all => "-background white" } }
Paperclip::Attachment.default_options.merge!(@new_default_options)
end
teardown do
after do
Paperclip::Attachment.default_options.merge!(@old_default_options)
end
should "deep merge when it is overridden" do
it "deep merge when it is overridden" do
new_options = { :convert_options => { :thumb => "-thumbnailize" } }
attachment = Paperclip::Attachment.new(:name, :instance, new_options)
assert_equal Paperclip::Attachment.default_options.deep_merge(new_options),
attachment.instance_variable_get("@options")
expect(Paperclip::Attachment.default_options.deep_merge(new_options)).to eq attachment.instance_variable_get("@options")
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
attachment = Paperclip::Attachment.new(:name, :instance, :url_generator => mock_url_generator_builder)
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)
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
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
attachment = Paperclip::Attachment.new(:name, :instance, :url_generator => mock_url_generator_builder)
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
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
attachment = Paperclip::Attachment.new(:name,
:instance,
......@@ -112,7 +100,7 @@ class AttachmentTest < Test::Unit::TestCase
assert mock_url_generator_builder.has_generated_url_with_options?(:escape => true, :timestamp => true)
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
attachment = Paperclip::Attachment.new(:name,
:instance,
......@@ -125,7 +113,7 @@ class AttachmentTest < Test::Unit::TestCase
assert mock_url_generator_builder.has_generated_url_with_style_name?('default style')
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
attachment = Paperclip::Attachment.new(:name,
:instance,
......@@ -136,7 +124,7 @@ class AttachmentTest < Test::Unit::TestCase
assert mock_url_generator_builder.has_generated_url_with_options?(:escape => true, :timestamp => true)
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
attachment = Paperclip::Attachment.new(:name,
:instance,
......@@ -147,7 +135,7 @@ class AttachmentTest < Test::Unit::TestCase
assert mock_url_generator_builder.has_generated_url_with_options?(:escape => true, :timestamp => false)
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
attachment = Paperclip::Attachment.new(:name,
:instance,
......@@ -158,7 +146,7 @@ class AttachmentTest < Test::Unit::TestCase
assert mock_url_generator_builder.has_generated_url_with_options?(:escape => true, :timestamp => true)
end
should "render JSON as default style" do
it "render JSON as default style" do
mock_url_generator_builder = MockUrlGeneratorBuilder.new
attachment = Paperclip::Attachment.new(:name,
:instance,
......@@ -169,7 +157,7 @@ class AttachmentTest < Test::Unit::TestCase
assert mock_url_generator_builder.has_generated_url_with_style_name?('default style')
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
attachment = Paperclip::Attachment.new(:name,
:instance,
......@@ -180,7 +168,7 @@ class AttachmentTest < Test::Unit::TestCase
assert mock_url_generator_builder.has_generated_url_with_options?(:escape => true)
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
attachment = Paperclip::Attachment.new(:name,
:instance,
......@@ -191,7 +179,7 @@ class AttachmentTest < Test::Unit::TestCase
assert mock_url_generator_builder.has_generated_url_with_options?(:escape => false)
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"
@model = @attachment.instance
@model.id = 1234
......@@ -199,7 +187,7 @@ class AttachmentTest < Test::Unit::TestCase
assert_equal "#{Rails.root}/public/fake_models/1234/fake", @attachment.path
end
should "default to a path that scales" do
it "default to a path that scales" do
avatar_attachment = attachment
model = avatar_attachment.instance
model.id = 1234
......@@ -208,7 +196,7 @@ class AttachmentTest < Test::Unit::TestCase
assert_equal expected_path, avatar_attachment.path
end
should "render JSON as the URL to the attachment" do
it "render JSON as the URL to the attachment" do
avatar_attachment = attachment
model = avatar_attachment.instance
model.id = 1234
......@@ -216,7 +204,7 @@ class AttachmentTest < Test::Unit::TestCase
assert_equal attachment.url, attachment.as_json
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
dummy = Dummy.new
dummy.id = 1234
......@@ -230,7 +218,7 @@ class AttachmentTest < Test::Unit::TestCase
end
context "Attachment default_options" do
setup do
before do
rebuild_model
@old_default_options = Paperclip::Attachment.default_options.dup
@new_default_options = @old_default_options.merge({
......@@ -240,11 +228,11 @@ class AttachmentTest < Test::Unit::TestCase
})
end
teardown do
after do
Paperclip::Attachment.default_options.merge! @old_default_options
end
should "be overrideable" do
it "be overrideable" do
Paperclip::Attachment.default_options.merge!(@new_default_options)
@new_default_options.keys.each do |key|
assert_equal @new_default_options[key],
......@@ -253,41 +241,41 @@ class AttachmentTest < Test::Unit::TestCase
end
context "without an Attachment" do
setup do
before do
@dummy = Dummy.new
end
should "return false when asked exists?" do
it "return false when asked exists?" do
assert !@dummy.avatar.exists?
end
end
context "on an Attachment" do
setup do
before do
@dummy = Dummy.new
@attachment = @dummy.avatar
end
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],
@attachment.instance_variable_get("@options")[key],
key
key.to_s
end
end
context "when redefined" do
setup do
before do
Paperclip::Attachment.default_options.merge!(@new_default_options)
@dummy = Dummy.new
@attachment = @dummy.avatar
end
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],
@attachment.instance_variable_get("@options")[key],
key
key.to_s
end
end
end
......@@ -295,7 +283,7 @@ class AttachmentTest < Test::Unit::TestCase
end
context "An attachment with similarly named interpolations" do
setup do
before do
rebuild_model :path => ":id.omg/:id-bbq/:idwhat/:id_partition.wtf"
@dummy = Dummy.new
@dummy.stubs(:id).returns(1024)
......@@ -303,15 +291,15 @@ class AttachmentTest < Test::Unit::TestCase
@dummy.avatar = @file
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
end
end
context "An attachment with :timestamp interpolations" do
setup do
before do
@file = StringIO.new("...")
@zone = 'UTC'
Time.stubs(:zone).returns(@zone)
......@@ -320,47 +308,47 @@ class AttachmentTest < Test::Unit::TestCase
end
context "using default time zone" do
setup do
before do
rebuild_model :path => ":timestamp", :use_default_time_zone => true
@dummy = Dummy.new
@dummy.avatar = @file
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
end
end
context "using per-thread time zone" do
setup do
before do
rebuild_model :path => ":timestamp", :use_default_time_zone => false
@dummy = Dummy.new
@dummy.avatar = @file
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
end
end
end
context "An attachment with :hash interpolations" do
setup do
before do
@file = StringIO.new("...\n")
end
should "raise if no secret is provided" do
it "raise if no secret is provided" do
rebuild_model :path => ":hash"
@attachment = Dummy.new.avatar
@attachment.assign @file
assert_raise ArgumentError do
assert_raises ArgumentError do
@attachment.path
end
end
context "when secret is set" do
setup do
before do
rebuild_model :path => ":hash",
:hash_secret => "w00t",
:hash_data => ":class/:attachment/:style/:filename"
......@@ -368,14 +356,14 @@ class AttachmentTest < Test::Unit::TestCase
@attachment.assign @file
end
should "result in the correct interpolation" do
it "result in the correct interpolation" do
assert_equal "dummies/avatars/original/data.txt",
@attachment.send(:interpolate, @attachment.options[:hash_data])
assert_equal "dummies/avatars/thumb/data.txt",
@attachment.send(:interpolate, @attachment.options[:hash_data], :thumb)
end
should "result in a correct hash" do
it "result in a correct hash" do
assert_equal "e1079a5c34ddbd197ebd0280d07952d98a57fb30", @attachment.path
assert_equal "d740189bd3e49ef226fab84c8d45f7ae4126d043", @attachment.path(:thumb)
end
......@@ -383,7 +371,7 @@ class AttachmentTest < Test::Unit::TestCase
end
context "An attachment with a :rails_env interpolation" do
setup do
before do
@rails_env = "blah"
@id = 1024
rebuild_model :path => ":rails_env/:id.png"
......@@ -394,13 +382,13 @@ class AttachmentTest < Test::Unit::TestCase
Rails.stubs(:env).returns(@rails_env)
end
should "return the proper path" do
it "return the proper path" do
assert_equal "#{@rails_env}/#{@id}.png", @dummy.avatar.path
end
end
context "An attachment with a default style and an extension interpolation" do
setup do
before do
rebuild_model :path => ":basename.:extension",
:styles => { :default => ["100x100", :jpg] },
:default_style => :default
......@@ -408,14 +396,14 @@ class AttachmentTest < Test::Unit::TestCase
@file = File.open(fixture_file("5k.png"))
@file.stubs(:original_filename).returns("file.png")
end
should "return the right extension for the path" do
it "return the right extension for the path" do
@attachment.assign(@file)
assert_equal "file.jpg", @attachment.path
end
end
context "An attachment with :convert_options" do
setup do
before do
rebuild_model :styles => {
:thumb => "100x100",
:large => "400x400"
......@@ -428,17 +416,17 @@ class AttachmentTest < Test::Unit::TestCase
@dummy.avatar
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
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)
end
end
context "An attachment with :source_file_options" do
setup do
before do
rebuild_model :styles => {
:thumb => "100x100",
:large => "400x400"
......@@ -451,17 +439,17 @@ class AttachmentTest < Test::Unit::TestCase
@dummy.avatar
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
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)
end
end
context "An attachment with :only_process" do
setup do
before do
rebuild_model :styles => {
:thumb => "100x100",
:large => "400x400"
......@@ -471,7 +459,7 @@ class AttachmentTest < Test::Unit::TestCase
@attachment = Dummy.new.avatar
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(:large).never
@attachment.assign(@file)
......@@ -479,7 +467,7 @@ class AttachmentTest < Test::Unit::TestCase
end
context "An attachment with :only_process that is a proc" do
setup do
before do
rebuild_model :styles => {
:thumb => "100x100",
:large => "400x400"
......@@ -490,7 +478,7 @@ class AttachmentTest < Test::Unit::TestCase
@attachment = Dummy.new.avatar
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(:large).never
@attachment.assign(@file)
......@@ -498,7 +486,7 @@ class AttachmentTest < Test::Unit::TestCase
end
context "An attachment with :convert_options that is a proc" do
setup do
before do
rebuild_model :styles => {
:thumb => "100x100",
:large => "400x400"
......@@ -515,17 +503,17 @@ class AttachmentTest < Test::Unit::TestCase
@dummy.avatar
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
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)
end
end
context "An attachment with :path that is a proc" do
setup do
before do
rebuild_model :path => lambda{ |attachment| "path/#{attachment.instance.other}.:extension" }
@file = File.new(fixture_file("5k.png"), 'rb')
......@@ -535,34 +523,34 @@ class AttachmentTest < Test::Unit::TestCase
@dummyB.avatar = @file
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/b.png", @dummyB.avatar.path
end
end
context "An attachment with :styles that is a proc" do
setup do
before do
rebuild_model :styles => lambda{ |attachment| {:thumb => "50x50#", :large => "400x400"} }
@attachment = Dummy.new.avatar
end
should "have the correct geometry" do
it "have the correct geometry" do
assert_equal "50x50#", @attachment.styles[:thumb][:geometry]
end
end
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"} }
@dummy = Dummy.new(:other => 'a')
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_nil @dummy.avatar.styles[:large]
......@@ -580,18 +568,18 @@ class AttachmentTest < Test::Unit::TestCase
]
geometry_specs.each do |geometry_spec|
context "An attachment geometry like #{geometry_spec}" do
setup do
before do
rebuild_model :styles => { :normal => geometry_spec }
@attachment = Dummy.new.avatar
end
context "when assigned" do
setup do
before do
@file = StringIO.new(".")
@attachment.assign(@file)
end
should "have the correct geometry" do
it "have the correct geometry" do
assert_equal "50x50#", @attachment.styles[:normal][:geometry]
end
end
......@@ -599,7 +587,7 @@ class AttachmentTest < Test::Unit::TestCase
end
context "An attachment with both 'normal' and hash-style styles" do
setup do
before do
rebuild_model :styles => {
:normal => ["50x50#", :png],
:hash => { :geometry => "50x50#", :format => :png }
......@@ -609,14 +597,14 @@ class AttachmentTest < Test::Unit::TestCase
end
[: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]
end
end
end
context "An attachment with :processors that is a proc" do
setup do
before do
class Paperclip::Test < Paperclip::Processor; end
@file = StringIO.new("...")
Paperclip::Test.stubs(:make).returns(@file)
......@@ -626,18 +614,18 @@ class AttachmentTest < Test::Unit::TestCase
end
context "when assigned" do
setup do
before do
@attachment.assign(StringIO.new("."))
end
should "have the correct processors" do
it "have the correct processors" do
assert_equal [ :test ], @attachment.styles[:normal][:processors]
end
end
end
context "An attachment with erroring processor" do
setup do
before do
rebuild_model :processor => [:thumbnail], :styles => { :small => '' }, :whiny_thumbnails => true
@dummy = Dummy.new
Paperclip::Thumbnail.expects(:make).raises(Paperclip::Error, "cannot be processed.")
......@@ -646,14 +634,14 @@ class AttachmentTest < Test::Unit::TestCase
@dummy.avatar = @file
end
should "correctly forward processing error message to the instance" do
it "correctly forward processing error message to the instance" do
@dummy.valid?
assert_contains @dummy.errors.full_messages, "Avatar cannot be processed."
end
end
context "An attachment with multiple processors" do
setup do
before do
class Paperclip::Test < Paperclip::Processor; end
@style_params = { :once => {:one => 1, :two => 2} }
rebuild_model :processors => [:thumbnail, :test], :styles => @style_params
......@@ -665,36 +653,47 @@ class AttachmentTest < Test::Unit::TestCase
end
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)
@dummy.avatar = @file
before_should "call #make on all specified processors" do
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
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({
:processors => [:thumbnail, :test],
:whiny => true,
:convert_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
before_should "call #make with attachment passed as third argument" do
Paperclip::Test.expects(:make).with(anything, anything, @dummy.avatar).returns(@file)
it "call #make with attachment passed as third argument" do
Paperclip::Test.expects(:make).returns(@file)
@dummy.avatar = @file
expect(Paperclip::Test).to have_received(:make).with(anything, anything, @dummy.avatar)
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
@dummy = Dummy.new
assert @dummy.avatar.is_a?(Paperclip::Storage::Filesystem)
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
@dummy = Dummy.new
assert @dummy.avatar.is_a?(Paperclip::Storage::Filesystem)
......@@ -704,16 +703,15 @@ class AttachmentTest < Test::Unit::TestCase
assert @dummy.avatar.is_a?(Paperclip::Storage::Filesystem)
end
should "convert underscored storage name to camelcase" do
it "convert underscored storage name to camelcase" do
rebuild_model :storage => :not_here
@dummy = Dummy.new
exception = assert_raises(Paperclip::Errors::StorageMethodNotFound) do
exception = assert_raises(Paperclip::Errors::StorageMethodNotFound, /NotHere/) do
@dummy.avatar
end
assert exception.message.include?("NotHere")
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
@dummy = Dummy.new
assert_raises(Paperclip::Errors::StorageMethodNotFound) do
......@@ -722,29 +720,29 @@ class AttachmentTest < Test::Unit::TestCase
end
context "An attachment with styles but no processors defined" do
setup do
before do
rebuild_model :processors => [], :styles => {:something => '1'}
@dummy = Dummy.new
@file = StringIO.new("...")
end
should "raise when assigned to" do
it "raise when assigned to" do
assert_raises(RuntimeError){ @dummy.avatar = @file }
end
end
context "An attachment without styles and with no processors defined" do
setup do
before do
rebuild_model :processors => [], :styles => {}
@dummy = Dummy.new
@file = StringIO.new("...")
end
should "not raise when assigned to" do
it "not raise when assigned to" do
@dummy.avatar = @file
end
end
context "Assigning an attachment with post_process hooks" do
setup do
before do
rebuild_class :styles => { :something => "100x100#" }
Dummy.class_eval do
before_avatar_post_process :do_before_avatar
......@@ -763,7 +761,7 @@ class AttachmentTest < Test::Unit::TestCase
@attachment = @dummy.avatar
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_after_avatar).with()
@dummy.expects(:do_before_all).with()
......@@ -772,7 +770,7 @@ class AttachmentTest < Test::Unit::TestCase
@dummy.avatar = @file
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_after_avatar).with()
@dummy.expects(:do_before_all).with().returns(nil)
......@@ -781,7 +779,7 @@ class AttachmentTest < Test::Unit::TestCase
@dummy.avatar = @file
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_after_avatar).never
@dummy.expects(:do_before_all).with().returns(false)
......@@ -790,7 +788,7 @@ class AttachmentTest < Test::Unit::TestCase
@dummy.avatar = @file
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_after_avatar)
@dummy.expects(:do_before_all).with().returns(true)
......@@ -801,37 +799,37 @@ class AttachmentTest < Test::Unit::TestCase
end
context "Assigning an attachment" do
setup do
before do
rebuild_model :styles => { :something => "100x100#" }
@file = File.new(fixture_file("5k.png"), "rb")
@dummy = Dummy.new
@dummy.avatar = @file
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
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
end
end
context "Assigning an attachment" do
setup do
before do
rebuild_model :styles => { :something => "100x100#" }
@file = File.new(fixture_file("5k.png"), "rb")
@dummy = Dummy.new
@dummy.avatar = @file
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
end
end
context "Attachment with strange letters" do
setup do
before do
rebuild_model
@file = File.new(fixture_file("5k.png"), "rb")
@file.stubs(:original_filename).returns("sheep_say_bæ.png")
......@@ -839,18 +837,18 @@ class AttachmentTest < Test::Unit::TestCase
@dummy.avatar = @file
end
should "not remove strange letters" do
it "not remove strange letters" do
assert_equal "sheep_say_bæ.png", @dummy.avatar.original_filename
end
end
context "Attachment with reserved filename" do
setup do
before do
rebuild_model
@file = Tempfile.new(["filename","png"])
end
teardown do
after do
@file.unlink
end
......@@ -859,37 +857,37 @@ class AttachmentTest < Test::Unit::TestCase
context "with character #{character}" do
context "at beginning of filename" do
setup do
before do
@file.stubs(:original_filename).returns("#{character}filename.png")
@dummy = Dummy.new
@dummy.avatar = @file
end
should "convert special character into underscore" do
it "convert special character into underscore" do
assert_equal "_filename.png", @dummy.avatar.original_filename
end
end
context "at end of filename" do
setup do
before do
@file.stubs(:original_filename).returns("filename.png#{character}")
@dummy = Dummy.new
@dummy.avatar = @file
end
should "convert special character into underscore" do
it "convert special character into underscore" do
assert_equal "filename.png_", @dummy.avatar.original_filename
end
end
context "in the middle of filename" do
setup do
before do
@file.stubs(:original_filename).returns("file#{character}name.png")
@dummy = Dummy.new
@dummy.avatar = @file
end
should "convert special character into underscore" do
it "convert special character into underscore" do
assert_equal "file_name.png", @dummy.avatar.original_filename
end
end
......@@ -899,16 +897,16 @@ class AttachmentTest < Test::Unit::TestCase
end
context "with specified regexp replacement" do
setup do
before do
@old_defaults = Paperclip::Attachment.default_options.dup
end
teardown do
after do
Paperclip::Attachment.default_options.merge! @old_defaults
end
context 'as another regexp' do
setup do
before do
Paperclip::Attachment.default_options.merge! :restricted_characters => /o/
@file.stubs(:original_filename).returns("goood.png")
......@@ -916,13 +914,13 @@ class AttachmentTest < Test::Unit::TestCase
@dummy.avatar = @file
end
should "match and convert that character" do
it "match and convert that character" do
assert_equal "g___d.png", @dummy.avatar.original_filename
end
end
context 'as nil' do
setup do
before do
Paperclip::Attachment.default_options.merge! :restricted_characters => nil
@file.stubs(:original_filename).returns("goood.png")
......@@ -930,22 +928,22 @@ class AttachmentTest < Test::Unit::TestCase
@dummy.avatar = @file
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
end
end
end
context 'with specified cleaner' do
setup do
before do
@old_defaults = Paperclip::Attachment.default_options.dup
end
teardown do
after do
Paperclip::Attachment.default_options.merge! @old_defaults
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|
"from_proc_#{str}"
end
......@@ -956,7 +954,7 @@ class AttachmentTest < Test::Unit::TestCase
assert_equal "from_proc_goood.png", @dummy.avatar.original_filename
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
def call(filename)
"foo"
......@@ -973,7 +971,7 @@ class AttachmentTest < Test::Unit::TestCase
end
context "Attachment with uppercase extension and a default style" do
setup do
before do
@old_defaults = Paperclip::Attachment.default_options.dup
Paperclip::Attachment.default_options.merge!({
:path => ":rails_root/:attachment/:class/:style/:id/:basename.:extension"
......@@ -995,23 +993,23 @@ class AttachmentTest < Test::Unit::TestCase
@attachment.save
end
teardown do
after do
@file.close
Paperclip::Attachment.default_options.merge!(@old_defaults)
end
should "should have matching to_s and url methods" do
assert_match @attachment.to_s, @attachment.url
assert_match @attachment.to_s(:small), @attachment.url(:small)
it "should have matching to_s and url methods" do
assert_equal @attachment.to_s, @attachment.url
assert_equal @attachment.to_s(:small), @attachment.url(:small)
end
should "have matching expiring_url and url methods when using the filesystem storage" do
assert_match @attachment.expiring_url, @attachment.url
it "have matching expiring_url and url methods when using the filesystem storage" do
assert_equal @attachment.expiring_url, @attachment.url
end
end
context "An attachment" do
setup do
before do
@old_defaults = Paperclip::Attachment.default_options.dup
Paperclip::Attachment.default_options.merge!({
:path => ":rails_root/:attachment/:class/:style/:id/:basename.:extension"
......@@ -1025,39 +1023,39 @@ class AttachmentTest < Test::Unit::TestCase
@file = File.new(fixture_file("5k.png"), 'rb')
end
teardown do
after do
@file.close
Paperclip::Attachment.default_options.merge!(@old_defaults)
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)
assert_raises(Paperclip::Error) do
@other_attachment.assign(@file)
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.queued_for_write[:original]
@attachment.assign(nil)
assert_nil @attachment.queued_for_write[:original]
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)
original_file = @attachment.queued_for_write[:original]
@attachment.assign("")
assert_equal original_file, @attachment.queued_for_write[:original]
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(:blah)
end
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)
assert !@attachment.queued_for_write.blank?
@attachment.clear
......@@ -1066,7 +1064,7 @@ class AttachmentTest < Test::Unit::TestCase
end
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(:content_type).returns("image/png")
@attachment.stubs(:instance_read).with(:file_size).returns(12345)
......@@ -1076,17 +1074,17 @@ class AttachmentTest < Test::Unit::TestCase
@attachment.stubs(:instance_read).with(:updated_at).returns(dtnow)
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)
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")
assert_equal File.expand_path("tmp/avatars/dummies/original/#{@instance.id}/5k.old.png"), File.expand_path(@attachment.path)
end
context "when expecting three styles" do
setup do
before do
rebuild_class :styles => {
:large => ["400x400", :png],
:medium => ["100x100", :gif],
......@@ -1099,28 +1097,28 @@ class AttachmentTest < Test::Unit::TestCase
end
context "and assigned a file" do
setup do
before do
now = Time.now
Time.stubs(:now).returns(now)
@attachment.assign(@file)
end
should "be dirty" do
it "be dirty" do
assert @attachment.dirty?
end
context "and saved" do
setup do
before do
@attachment.save
end
should "commit the files to disk" do
it "commit the files to disk" do
[:large, :medium, :small].each do |style|
assert_file_exists(@attachment.path(style))
expect(@attachment.path(style)).to exist
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"],
[:medium, 100, 15, "GIF"],
[:small, 32, 32, "JPEG"]].each do |style|
......@@ -1134,13 +1132,13 @@ class AttachmentTest < Test::Unit::TestCase
end
context "and trying to delete" do
setup do
before do
@existing_names = @attachment.styles.keys.collect do |style|
@attachment.path(style)
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(:content_type, nil)
@attachment.expects(:instance_write).with(:file_size, nil)
......@@ -1151,7 +1149,7 @@ class AttachmentTest < Test::Unit::TestCase
@existing_names.each{|f| assert_file_not_exists(f) }
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(:content_type, nil)
@attachment.expects(:instance_write).with(:file_size, nil)
......@@ -1162,7 +1160,7 @@ class AttachmentTest < Test::Unit::TestCase
@existing_names.each{|f| assert_file_not_exists(f) }
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(:content_type, nil)
@attachment.expects(:instance_write).with(:file_size, nil)
......@@ -1173,11 +1171,11 @@ class AttachmentTest < Test::Unit::TestCase
end
context "when keeping old files" do
setup do
before do
@attachment.options[:keep_old_files] = true
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(:content_type, nil)
@attachment.expects(:instance_write).with(:file_size, nil)
......@@ -1188,7 +1186,7 @@ class AttachmentTest < Test::Unit::TestCase
@existing_names.each{|f| assert_file_exists(f) }
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(:content_type, nil)
@attachment.expects(:instance_write).with(:file_size, nil)
......@@ -1199,7 +1197,7 @@ class AttachmentTest < Test::Unit::TestCase
@existing_names.each{|f| assert_file_exists(f) }
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(:content_type, nil)
@attachment.expects(:instance_write).with(:file_size, nil)
......@@ -1216,18 +1214,18 @@ class AttachmentTest < Test::Unit::TestCase
end
context "when trying a nonexistant storage type" do
setup do
before do
rebuild_model :storage => :not_here
end
should "not be able to find the module" do
assert_raise(Paperclip::Errors::StorageMethodNotFound){ Dummy.new.avatar }
it "not be able to find the module" do
assert_raises(Paperclip::Errors::StorageMethodNotFound){ Dummy.new.avatar }
end
end
end
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|
table.column :avatar_file_name, :string
end
......@@ -1236,41 +1234,41 @@ class AttachmentTest < Test::Unit::TestCase
@file = File.new(fixture_file("5k.png"), 'rb')
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 }
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
assert_nil @dummy.avatar.updated_at
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
assert_equal File.size(@file), @dummy.avatar.size
end
context "and avatar_created_at column" do
setup do
before do
ActiveRecord::Base.connection.add_column :dummies, :avatar_created_at, :timestamp
rebuild_class
@dummy = Dummy.new
end
should "not error when assigned an attachment" do
it "not error when assigned an attachment" do
assert_nothing_raised { @dummy.avatar = @file }
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
Time.stubs(:now).returns(now)
@dummy.avatar = @file
assert_equal now.to_i, @dummy.avatar.created_at
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
now = Time.now
Time.stubs(:now).returns(creation)
......@@ -1281,7 +1279,7 @@ class AttachmentTest < Test::Unit::TestCase
assert_not_equal now.to_i, @dummy.avatar.created_at
end
should "set changed? to true on attachment assignment" do
it "set changed? to true on attachment assignment" do
@dummy.avatar = @file
@dummy.save!
@dummy.avatar = @file
......@@ -1290,17 +1288,17 @@ class AttachmentTest < Test::Unit::TestCase
end
context "and avatar_updated_at column" do
setup do
before do
ActiveRecord::Base.connection.add_column :dummies, :avatar_updated_at, :timestamp
rebuild_class
@dummy = Dummy.new
end
should "not error when assigned an attachment" do
it "not error when assigned an attachment" do
assert_nothing_raised { @dummy.avatar = @file }
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
Time.stubs(:now).returns(now)
@dummy.avatar = @file
......@@ -1308,45 +1306,45 @@ class AttachmentTest < Test::Unit::TestCase
end
end
should "not calculate fingerprint" do
it "not calculate fingerprint" do
@dummy.avatar = @file
assert_nil @dummy.avatar.fingerprint
end
context "and avatar_content_type column" do
setup do
before do
ActiveRecord::Base.connection.add_column :dummies, :avatar_content_type, :string
rebuild_class
@dummy = Dummy.new
end
should "not error when assigned an attachment" do
it "not error when assigned an attachment" do
assert_nothing_raised { @dummy.avatar = @file }
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
assert_equal "image/png", @dummy.avatar.content_type
end
end
context "and avatar_file_size column" do
setup do
before do
ActiveRecord::Base.connection.add_column :dummies, :avatar_file_size, :integer
rebuild_class
@dummy = Dummy.new
end
should "not error when assigned an attachment" do
it "not error when assigned an attachment" do
assert_nothing_raised { @dummy.avatar = @file }
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
assert_equal File.size(@file), @dummy.avatar.size
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.save
@dummy = Dummy.find(@dummy.id)
......@@ -1355,22 +1353,22 @@ class AttachmentTest < Test::Unit::TestCase
end
context "and avatar_fingerprint column" do
setup do
before do
ActiveRecord::Base.connection.add_column :dummies, :avatar_fingerprint, :string
rebuild_class
@dummy = Dummy.new
end
should "not error when assigned an attachment" do
it "not error when assigned an attachment" do
assert_nothing_raised { @dummy.avatar = @file }
end
should "return the right value when sent #avatar_fingerprint" do
it "return the right value when sent #avatar_fingerprint" do
@dummy.avatar = @file
assert_equal 'aec488126c3b33c08a10c3fa303acf27', @dummy.avatar_fingerprint
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.save
@dummy = Dummy.find(@dummy.id)
......@@ -1380,7 +1378,7 @@ class AttachmentTest < Test::Unit::TestCase
end
context "an attachment with delete_file option set to false" do
setup do
before do
rebuild_model :preserve_files => true
@dummy = Dummy.new
@file = File.new(fixture_file("5k.png"), 'rb')
......@@ -1390,27 +1388,27 @@ class AttachmentTest < Test::Unit::TestCase
@path = @attachment.path
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
assert_file_exists(@path)
end
should "clear out attachment data when attachment is destroyed" do
it "clear out attachment data when attachment is destroyed" do
@attachment.destroy
assert !@attachment.exists?
assert_nil @dummy.avatar_file_name
end
should "not delete the file when model is destroyed" do
it "not delete the file when model is destroyed" do
@dummy.destroy
assert_file_exists(@path)
end
end
context "An attached file" do
setup do
before do
rebuild_model
@dummy = Dummy.new
@file = File.new(fixture_file("5k.png"), 'rb')
......@@ -1420,24 +1418,24 @@ class AttachmentTest < Test::Unit::TestCase
@path = @attachment.path
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)
assert_raise Exception do
assert_raises Exception do
@dummy.destroy
end
assert_file_exists(@path)
end
should "be deleted when the model is destroyed" do
it "be deleted when the model is destroyed" do
@dummy.destroy
assert_file_not_exists(@path)
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
@dummy.destroy
raise ActiveRecord::Rollback
......@@ -1448,3 +1446,4 @@ class AttachmentTest < Test::Unit::TestCase
end
end
require './test/helper'
require 'spec_helper'
class ContentTypeDetectorTest < Test::Unit::TestCase
should 'give a sensible default when the name is empty' do
describe Paperclip::ContentTypeDetector do
it 'give a sensible default when the name is empty' do
assert_equal "application/octet-stream", Paperclip::ContentTypeDetector.new("").detect
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")
assert_equal "inode/x-empty", Paperclip::ContentTypeDetector.new(tempfile.path).detect
tempfile.close
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')])
Paperclip.stubs(:run).returns("video/mp4")
@filename = "my_file.mp4"
assert_equal "video/mp4", Paperclip::ContentTypeDetector.new(@filename).detect
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"
File.open(@filename, "w+") do |file|
file.puts "This is a text file."
......@@ -28,12 +28,12 @@ class ContentTypeDetectorTest < Test::Unit::TestCase
FileUtils.rm @filename
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"
assert_equal "application/octet-stream", Paperclip::ContentTypeDetector.new(@filename).detect
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)
@filename = "/path/to/something"
assert_equal "application/octet-stream", Paperclip::ContentTypeDetector.new(@filename).detect
......
require './test/helper'
require 'spec_helper'
class FileCommandContentTypeDetectorTest < Test::Unit::TestCase
should 'return a content type based on the content of the file' do
describe Paperclip::FileCommandContentTypeDetector do
it 'return a content type based on the content of the file' do
tempfile = Tempfile.new("something")
tempfile.write("This is a file.")
tempfile.rewind
......@@ -11,14 +11,14 @@ class FileCommandContentTypeDetectorTest < Test::Unit::TestCase
tempfile.close
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)
@filename = "/path/to/something"
assert_equal "application/octet-stream",
Paperclip::FileCommandContentTypeDetector.new(@filename).detect
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)
assert_equal "application/octet-stream",
Paperclip::FileCommandContentTypeDetector.new("windows").detect
......
# encoding: utf-8
require './test/helper'
require 'spec_helper'
class FilenameCleanerTest < Test::Unit::TestCase
should 'convert invalid characters to underscores' do
describe Paperclip::FilenameCleaner do
it 'convert invalid characters to underscores' do
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
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)
assert_equal "baseball", cleaner.call("baseball")
expect(cleaner.call("baseball")).to eq "baseball"
end
end
require './test/helper'
require 'spec_helper'
class GeometryDetectorTest < Test::Unit::TestCase
should 'identify an image and extract its dimensions' do
describe Paperclip::GeometryDetector do
it 'identify an image and extract its dimensions' do
Paperclip::GeometryParser.stubs(:new).with("434x66,").returns(stub(:make => :correct))
file = fixture_file("5k.png")
factory = Paperclip::GeometryDetector.new(file)
output = factory.make
assert_equal :correct, output
expect(output).to eq :correct
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))
file = fixture_file("rotated.jpg")
factory = Paperclip::GeometryDetector.new(file)
output = factory.make
assert_equal :correct, output
expect(output).to eq :correct
end
end
require './test/helper'
require 'spec_helper'
class GeometryParserTest < Test::Unit::TestCase
should 'identify an image and extract its dimensions with no orientation' do
describe Paperclip::GeometryParser do
it 'identify an image and extract its dimensions with no orientation' do
Paperclip::Geometry.stubs(:new).with(
:height => '73',
:width => '434',
......@@ -15,7 +15,7 @@ class GeometryParserTest < Test::Unit::TestCase
assert_equal :correct, output
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(
:height => '73',
:width => '434',
......@@ -29,7 +29,7 @@ class GeometryParserTest < Test::Unit::TestCase
assert_equal :correct, output
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(
:height => '200',
:width => '300',
......@@ -43,7 +43,7 @@ class GeometryParserTest < Test::Unit::TestCase
assert_equal :correct, output
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(
:height => '64',
:width => '64',
......@@ -57,7 +57,7 @@ class GeometryParserTest < Test::Unit::TestCase
assert_equal :correct, output
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(
:height => '50',
:width => '100',
......
require './test/helper'
require 'spec_helper'
class GeometryTest < Test::Unit::TestCase
describe 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_equal 1024, @geo.width
assert_equal 768, @geo.height
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_equal 1024, @geo.width
assert_equal 0, @geo.height
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_equal 0, @geo.width
assert_equal 768, @geo.height
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_equal 800, @geo.width
assert_equal 600, @geo.height
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_equal 0, @geo.width
assert_equal 600, @geo.height
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_equal 800, @geo.width
assert_equal 0, @geo.height
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_equal 800, @geo.width
assert_equal 0, @geo.height
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_nil @geo.modifier
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)
assert geo
assert_equal 1024, geo.width
......@@ -61,7 +61,7 @@ class GeometryTest < Test::Unit::TestCase
assert_equal 768, geo.height
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)
assert geo
assert_equal 1024, geo.width
......@@ -73,7 +73,7 @@ class GeometryTest < Test::Unit::TestCase
assert_equal 1024, geo.height
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")
@upper = Paperclip::Geometry.parse("123X456")
assert_equal 123, @lower.width
......@@ -83,48 +83,46 @@ class GeometryTest < Test::Unit::TestCase
end
['>', '<', '#', '@', '%', '^', '!', 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_equal mod, @geo.modifier
assert_equal "123x456#{mod}", @geo.to_s
end
end
['>', '<', '#', '@', '%', '^', '!', nil].each do |mod|
should "ensure the modifier #{mod.inspect} is preserved with no height" do
it "ensure the modifier #{description} is preserved with no height" do
assert @geo = Paperclip::Geometry.parse("123x#{mod}")
assert_equal mod, @geo.modifier
assert_equal "123#{mod}", @geo.to_s
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 @dst = Paperclip::Geometry.parse("123x456>")
assert_equal ["123x456>", nil], @src.transformation_to(@dst)
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_equal "800", @geo.to_s
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_equal "800", @geo.to_s
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_equal "x600", @geo.to_s
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_equal "800x600", @geo.to_s
end
should "be generated from a file" do
it "be generated from a file" do
file = fixture_file("5k.png")
file = File.new(file, 'rb')
assert_nothing_raised{ @geo = Paperclip::Geometry.from_file(file) }
......@@ -132,14 +130,14 @@ class GeometryTest < Test::Unit::TestCase
assert_equal 434, @geo.width
end
should "be generated from a file path" do
it "be generated from a file path" do
file = fixture_file("5k.png")
assert_nothing_raised{ @geo = Paperclip::Geometry.from_file(file) }
assert_equal 66, @geo.height
assert_equal 434, @geo.width
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")
assert_nothing_raised{ @geo = Paperclip::Geometry.from_file(file) }
@geo.auto_orient
......@@ -147,28 +145,28 @@ class GeometryTest < Test::Unit::TestCase
assert_equal 200, @geo.width
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"
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
should "not generate from a blank filename" do
it "not generate from a blank filename" do
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
should "not generate from a nil file" do
it "not generate from a nil file" do
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
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.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
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']
begin
ENV['PATH'] = ''
......@@ -185,32 +183,32 @@ class GeometryTest < Test::Unit::TestCase
['horizontal', 1024, 768, false, true, false, 1024, 768, 1.3333],
['square', 100, 100, false, false, true, 100, 100, 1]].each do |args|
context "performing calculations on a #{args[0]} viewport" do
setup do
before do
@geo = Paperclip::Geometry.new(args[1], args[2])
end
should "#{args[3] ? "" : "not"} be vertical" do
it "#{args[3] ? "" : "not"} be vertical" do
assert_equal args[3], @geo.vertical?
end
should "#{args[4] ? "" : "not"} be horizontal" do
it "#{args[4] ? "" : "not"} be horizontal" do
assert_equal args[4], @geo.horizontal?
end
should "#{args[5] ? "" : "not"} be square" do
it "#{args[5] ? "" : "not"} be square" do
assert_equal args[5], @geo.square?
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
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
end
should "have an aspect ratio of #{args[8]}" do
assert_in_delta args[8], @geo.aspect, 0.0001
it "have an aspect ratio of #{args[8]}" do
expect(@geo.aspect).to be_within(0.0001).of(args[8])
end
end
end
......@@ -219,17 +217,17 @@ class GeometryTest < Test::Unit::TestCase
[ [100, 1000], [50, 950], "x950", "50x950+22+0" ],
[ [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
setup do
before do
@geo = Paperclip::Geometry.new(*args[0])
@dst = Paperclip::Geometry.new(*args[1])
@scale, @crop = @geo.transformation_to @dst, true
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
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
end
end
......@@ -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|
options.each_pair do |size, dimensions|
context "#{original_size} resize_to #{size}" do
setup do
before do
@source = Paperclip::Geometry.parse original_size
@new_geometry = @source.resize_to size
end
should "have #{dimensions.first} width" do
it "have #{dimensions.first} width" do
assert_equal dimensions.first, @new_geometry.width
end
should "have #{dimensions.last} height" do
it "have #{dimensions.last} height" do
assert_equal dimensions.last, @new_geometry.height
end
end
......
require './test/helper'
require 'paperclip/has_attached_file'
require 'spec_helper'
class HasAttachedFileTest < Test::Unit::TestCase
describe Paperclip::HasAttachedFile 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=')
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')
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?')
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')
end
should 'flush errors as part of validations' do
it 'flush errors as part of validations' do
assert_adding_attachment('avatar').defines_validation
end
should 'register the attachment with Paperclip::AttachmentRegistry' do
it 'register the attachment with Paperclip::AttachmentRegistry' do
assert_adding_attachment('avatar').registers_attachment
end
should 'define an after_save callback' do
it 'define an after_save callback' do
assert_adding_attachment('avatar').defines_callback('after_save')
end
should 'define a before_destroy callback' do
it 'define a before_destroy callback' do
assert_adding_attachment('avatar').defines_callback('before_destroy')
end
should 'define an after_commit callback' do
it 'define an after_commit callback' do
assert_adding_attachment('avatar').defines_callback('after_commit')
end
should 'define the Paperclip-specific callbacks' do
it 'define the Paperclip-specific callbacks' do
assert_adding_attachment('avatar').defines_callback('define_paperclip_callbacks')
end
end
......@@ -52,7 +51,7 @@ class HasAttachedFileTest < Test::Unit::TestCase
class AttachmentAdder
include Mocha::API
include Test::Unit::Assertions
include RSpec::Matchers
def initialize(attachment_name)
@attachment_name = attachment_name
......@@ -63,9 +62,7 @@ class HasAttachedFileTest < Test::Unit::TestCase
Paperclip::HasAttachedFile.define_on(a_class, @attachment_name, {})
assert_received(a_class, :define_method) do |expect|
expect.with(method_name)
end
expect(a_class).to have_received(:define_method).with(method_name)
end
def defines_class_method(method_name)
......@@ -74,9 +71,7 @@ class HasAttachedFileTest < Test::Unit::TestCase
Paperclip::HasAttachedFile.define_on(a_class, @attachment_name, {})
assert_received(a_class, :extend) do |expect|
expect.with(Paperclip::HasAttachedFile::ClassMethods)
end
expect(a_class).to have_received(:extend).with(Paperclip::HasAttachedFile::ClassMethods)
end
def defines_validation
......@@ -84,9 +79,7 @@ class HasAttachedFileTest < Test::Unit::TestCase
Paperclip::HasAttachedFile.define_on(a_class, @attachment_name, {})
assert_received(a_class, :validates_each) do |expect|
expect.with(@attachment_name)
end
expect(a_class).to have_received(:validates_each).with(@attachment_name)
end
def registers_attachment
......@@ -95,9 +88,7 @@ class HasAttachedFileTest < Test::Unit::TestCase
Paperclip::HasAttachedFile.define_on(a_class, @attachment_name, {size: 1})
assert_received(Paperclip::AttachmentRegistry, :register) do |expect|
expect.with(a_class, @attachment_name, {size: 1})
end
expect(Paperclip::AttachmentRegistry).to have_received(:register).with(a_class, @attachment_name, {size: 1})
end
def defines_callback(callback_name)
......@@ -105,7 +96,7 @@ class HasAttachedFileTest < Test::Unit::TestCase
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
private
......
# encoding: utf-8
require './test/helper'
require 'spec_helper'
require 'open-uri'
class IntegrationTest < Test::Unit::TestCase
describe 'Paperclip' do
context "Many models at once" do
setup do
before do
rebuild_model
@file = File.new(fixture_file("5k.png"), 'rb')
@file = File.new(fixture_file("5k.png"), 'rb')
300.times do |i|
Dummy.create! :avatar => @file
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
Dummy.all.each { |dummy| dummy.avatar }
end
......@@ -23,7 +22,7 @@ class IntegrationTest < Test::Unit::TestCase
end
context "An attachment" do
setup do
before do
rebuild_model :styles => { :thumb => "50x50#" }
@dummy = Dummy.new
@file = File.new(fixture_file("5k.png"), 'rb')
......@@ -31,16 +30,16 @@ class IntegrationTest < Test::Unit::TestCase
assert @dummy.save
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)}"`)
end
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
silence_stream(STDERR) do
@dummy.avatar.reprocess!
......@@ -48,17 +47,17 @@ class IntegrationTest < Test::Unit::TestCase
end
end
should "return false" do
it "return false" do
silence_stream(STDERR) do
assert !@dummy.avatar.reprocess!
end
end
teardown { File.chmod(0644, @dummy.avatar.path) }
# after { File.chmod(0644, @dummy.avatar.path) }
end
context "redefining its attachment styles" do
setup do
before do
Dummy.class_eval do
has_attached_file :avatar, :styles => { :thumb => "150x25#", :dynamic => lambda { |a| '50x50#' } }
end
......@@ -68,19 +67,19 @@ class IntegrationTest < Test::Unit::TestCase
@d2.save
end
should "create its thumbnails properly" do
it "create its thumbnails properly" do
assert_match(/\b150x25\b/, `identify "#{@dummy.avatar.path(:thumb)}"`)
assert_match(/\b50x50\b/, `identify "#{@dummy.avatar.path(:dynamic)}"`)
end
should "change the timestamp" do
it "change the timestamp" do
assert_not_equal @original_timestamp, @d2.avatar_updated_at
end
end
end
context "Attachment" do
setup do
before do
@thumb_path = "tmp/public/system/dummies/avatars/000/000/001/thumb/5k.png"
File.delete(@thumb_path) if File.exists?(@thumb_path)
rebuild_model :styles => { :thumb => "50x50#" }
......@@ -89,16 +88,16 @@ class IntegrationTest < Test::Unit::TestCase
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 = @file
assert @dummy.save
assert_file_not_exists @thumb_path
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 = @file
assert @dummy.save
......@@ -107,7 +106,7 @@ class IntegrationTest < Test::Unit::TestCase
end
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_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)
......@@ -122,9 +121,9 @@ class IntegrationTest < Test::Unit::TestCase
@dummy.avatar.post_processing = true
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_large_path)
......@@ -134,7 +133,7 @@ class IntegrationTest < Test::Unit::TestCase
assert_file_exists(@thumb_large_path)
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_large_path)
......@@ -148,22 +147,22 @@ class IntegrationTest < Test::Unit::TestCase
end
context "A model that modifies its original" do
setup do
before do
rebuild_model :styles => { :original => "2x2#" }
@dummy = Dummy.new
@file = File.new(fixture_file("5k.png"), 'rb')
@dummy.avatar = @file
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
end
teardown { @file.close }
# after { @file.close }
end
context "A model with attachments scoped under an id" do
setup do
before do
rebuild_model :styles => { :large => "100x100",
:medium => "50x50" },
:path => ":rails_root/tmp/:id/:attachments/:style.:extension"
......@@ -172,35 +171,41 @@ class IntegrationTest < Test::Unit::TestCase
@dummy.avatar = @file
end
teardown { @file.close }
# after { @file.close }
context "when saved" do
setup do
before do
@dummy.save
@saved_path = @dummy.avatar.path(:large)
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))
end
context "and deleted" do
setup do
before do
@dummy.avatar.clear
@dummy.save
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)
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(File.dirname(@saved_path)))
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)
assert_nothing_raised do
@dummy.avatar.clear
@dummy.save
end
end
end
end
......@@ -208,19 +213,19 @@ class IntegrationTest < Test::Unit::TestCase
[000,002,022].each do |umask|
context "when the umask is #{umask}" do
setup do
before do
rebuild_model
@dummy = Dummy.new
@file = File.new(fixture_file("5k.png"), 'rb')
@umask = File.umask(umask)
end
teardown do
File.umask @umask
@file.close
end
# after do
# File.umask @umask
# @file.close
# end
should "respect the current umask" do
it "respect the current umask" do
@dummy.avatar = @file
@dummy.save
assert_equal 0666&~umask, 0666&File.stat(@dummy.avatar.path).mode
......@@ -230,17 +235,17 @@ class IntegrationTest < Test::Unit::TestCase
[0666,0664,0640].each do |perms|
context "when the perms are #{perms}" do
setup do
before do
rebuild_model :override_file_permissions => perms
@dummy = Dummy.new
@file = File.new(fixture_file("5k.png"), 'rb')
end
teardown do
@file.close
end
# after do
# @file.close
# end
should "respect the current perms" do
it "respect the current perms" do
@dummy.avatar = @file
@dummy.save
assert_equal perms, File.stat(@dummy.avatar.path).mode & 0777
......@@ -248,7 +253,7 @@ class IntegrationTest < Test::Unit::TestCase
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
rebuild_model :override_file_permissions => false
......@@ -258,7 +263,7 @@ class IntegrationTest < Test::Unit::TestCase
end
context "A model with a filesystem attachment" do
setup do
before do
rebuild_model :styles => { :large => "300x300>",
:medium => "100x100",
:thumb => ["32x32#", :gif] },
......@@ -274,9 +279,9 @@ class IntegrationTest < Test::Unit::TestCase
assert @dummy.save
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],
["300x46", :large],
["100x15", :medium],
......@@ -314,7 +319,7 @@ class IntegrationTest < Test::Unit::TestCase
assert_nil @d2.avatar_file_name
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)
assert_equal @dummy.avatar_file_name, @d2.avatar_file_name
......@@ -332,18 +337,18 @@ class IntegrationTest < Test::Unit::TestCase
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
@dummy.avatar = "not a file"
end
end
should "not be ok with bad files" do
it "not be ok with bad files" do
@dummy.avatar = @bad_file
assert ! @dummy.valid?
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
@d2 = Dummy.find(@dummy.id)
@d2.avatar = @file
......@@ -352,7 +357,7 @@ class IntegrationTest < Test::Unit::TestCase
assert ! @d2.valid?
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
assert @dummy.save, @dummy.errors.full_messages.inspect
@dummy.avatar.clear
......@@ -362,31 +367,31 @@ class IntegrationTest < Test::Unit::TestCase
end
context "that is assigned its file from another Paperclip attachment" do
setup do
before do
@dummy2 = Dummy.new
@file2 = File.new(fixture_file("12k.png"), 'rb')
assert @dummy2.avatar = @file2
@file2 = File.new(fixture_file("12k.png"), 'rb')
assert @dummy2.avatar = @file2
@dummy2.save
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)}"`,
`identify -format "%wx%h" "#{@dummy2.avatar.path(:original)}"`
`identify -format "%wx%h" "#{@dummy2.avatar.path(:original)}"`
assert @dummy.avatar = @dummy2.avatar
@dummy.save
assert_equal @dummy.avatar_file_name, @dummy2.avatar_file_name
assert_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)}"`
end
end
end
context "A model with an attachments association and a Paperclip attachment" do
setup do
before do
Dummy.class_eval do
has_many :attachments, :class_name => 'Dummy'
end
......@@ -396,15 +401,15 @@ class IntegrationTest < Test::Unit::TestCase
@dummy.avatar = @file
end
teardown { @file.close }
# after { @file.close }
should "should not error when saving" do
it "should not error when saving" do
@dummy.save!
end
end
context "A model with an attachment with hash in file name" do
setup do
before do
@settings = { :styles => { :thumb => "50x50#" },
:path => ":rails_root/public/system/:attachment/:id_partition/:style/:hash.:extension",
:url => "/system/:attachment/:id_partition/:style/:hash.:extension",
......@@ -416,17 +421,17 @@ class IntegrationTest < Test::Unit::TestCase
@dummy = Dummy.create! :avatar => @file
end
teardown do
@file.close
end
# after do
# @file.close
# end
should "be accessible" do
it "be accessible" do
assert_file_exists(@dummy.avatar.path(:original))
assert_file_exists(@dummy.avatar.path(:thumb))
end
context "when new style is added" do
setup do
before do
@dummy.avatar.options[:styles][:mini] = "25x25#"
@dummy.avatar.instance_variable_set :@normalized_styles, nil
Time.stubs(:now => Time.now + 10)
......@@ -434,7 +439,7 @@ class IntegrationTest < Test::Unit::TestCase
@dummy.reload
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(:thumb))
assert_file_exists(@dummy.avatar.path(:mini))
......@@ -464,7 +469,7 @@ class IntegrationTest < Test::Unit::TestCase
end
context "A model with an S3 attachment" do
setup do
before do
rebuild_model :styles => { :large => "300x300>",
:medium => "100x100",
:thumb => ["32x32#", :gif],
......@@ -492,29 +497,29 @@ class IntegrationTest < Test::Unit::TestCase
@files_on_s3 = s3_files_for(@dummy.avatar)
end
teardown do
@file.close
@bad_file.close
@files_on_s3.values.each(&:close) if @files_on_s3
end
# after do
# @file.close
# @bad_file.close
# @files_on_s3.values.each(&:close) if @files_on_s3
# end
context 'assigning itself to a new model' do
setup do
before do
@d2 = Dummy.new
@d2.avatar = @dummy.avatar
@d2.save
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
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
end
should "write and delete its files" do
it "write and delete its files" do
[["434x66", :original],
["300x46", :large],
["100x15", :medium],
......@@ -546,7 +551,7 @@ class IntegrationTest < Test::Unit::TestCase
assert_nil @d2.avatar_file_name
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)
assert_equal @dummy.avatar_file_name, @d2.avatar_file_name
......@@ -570,7 +575,7 @@ class IntegrationTest < Test::Unit::TestCase
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
assert ! @dummy.valid?
@dummy.avatar = nil
......@@ -586,7 +591,7 @@ class IntegrationTest < Test::Unit::TestCase
assert ! @d2.valid?
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
assert @dummy.save
@dummy.avatar = nil
......@@ -595,28 +600,28 @@ class IntegrationTest < Test::Unit::TestCase
assert_equal "5k.png", @dummy.avatar_file_name
end
should "have the right content type" do
it "have the right content type" do
headers = s3_headers_for(@dummy.avatar, :original)
assert_equal 'image/png', headers['content-type']
end
should "have the right style-specific headers" do
it "have the right style-specific headers" do
headers = s3_headers_for(@dummy.avatar, :custom)
assert_equal 'max-age=31557600', headers['cache-control']
end
should "have the right style-specific metadata" do
it "have the right style-specific metadata" do
headers = s3_headers_for(@dummy.avatar, :custom)
assert_equal 'bar', headers['x-amz-meta-foo']
end
context "with non-english character in the file name" do
setup do
before do
@file.stubs(:original_filename).returns("クリップ.png")
@dummy.avatar = @file
end
should "not raise any error" do
it "not raise any error" do
@dummy.save!
end
end
......@@ -624,14 +629,14 @@ class IntegrationTest < Test::Unit::TestCase
end
context "Copying attachments between models" do
setup do
before do
rebuild_model
@file = File.new(fixture_file("5k.png"), 'rb')
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.avatar = @file
assert original.save
......@@ -643,7 +648,7 @@ class IntegrationTest < Test::Unit::TestCase
assert copy.avatar.present?
end
should "succeed when original attachment is empty" do
it "succeed when original attachment is empty" do
original = Dummy.create!
copy = Dummy.new
......
require './test/helper'
require 'spec_helper'
class InterpolationsTest < Test::Unit::TestCase
should "return all methods but the infrastructure when sent #all" do
describe Paperclip::Interpolations do
it "return all methods but the infrastructure when sent #all" do
methods = Paperclip::Interpolations.all
assert ! methods.include?(:[])
assert ! methods.include?(:[]=)
......@@ -11,39 +11,39 @@ class InterpolationsTest < Test::Unit::TestCase
end
end
should "return the Rails.root" do
it "return the Rails.root" do
assert_equal Rails.root, Paperclip::Interpolations.rails_root(:attachment, :style)
end
should "return the Rails.env" do
it "return the Rails.env" do
assert_equal Rails.env, Paperclip::Interpolations.rails_env(:attachment, :style)
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
end
should "return the class of the instance" do
it "return the class of the instance" do
attachment = mock
attachment.expects(:instance).returns(attachment)
attachment.expects(:class).returns("Thing")
assert_equal "things", Paperclip::Interpolations.class(attachment, :style)
end
should "return the basename of the file" do
it "return the basename of the file" do
attachment = mock
attachment.expects(:original_filename).returns("one.jpg").times(2)
assert_equal "one", Paperclip::Interpolations.basename(attachment, :style)
end
should "return the extension of the file" do
it "return the extension of the file" do
attachment = mock
attachment.expects(:original_filename).returns("one.jpg")
attachment.expects(:styles).returns({})
assert_equal "jpg", Paperclip::Interpolations.extension(attachment, :style)
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.expects(:original_filename).never
attachment.expects(:styles).twice.returns({:style => {:format => "png"}})
......@@ -53,7 +53,7 @@ class InterpolationsTest < Test::Unit::TestCase
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.expects(:content_type).returns('image/jpeg')
attachment.expects(:styles).returns({})
......@@ -62,7 +62,7 @@ class InterpolationsTest < Test::Unit::TestCase
assert_equal "jpeg", interpolations.content_type_extension(attachment, :style)
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.expects(:content_type).returns('image/jpeg')
attachment.expects(:styles).returns({})
......@@ -71,7 +71,7 @@ class InterpolationsTest < Test::Unit::TestCase
assert_equal "jpe", interpolations.content_type_extension(attachment, :style)
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.expects(:content_type).at_least_once().returns('not/found')
attachment.expects(:styles).returns({})
......@@ -80,7 +80,7 @@ class InterpolationsTest < Test::Unit::TestCase
assert_equal "found", interpolations.content_type_extension(attachment, :style)
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.expects(:content_type).returns('image/jpeg')
attachment.expects(:styles).returns({:style => {:format => "png"}})
......@@ -89,78 +89,78 @@ class InterpolationsTest < Test::Unit::TestCase
assert_equal "png", interpolations.content_type_extension(attachment, :style)
end
should "be able to handle numeric style names" do
it "be able to handle numeric style names" do
attachment = mock(
:styles => {:"4" => {:format => :expected_extension}}
)
assert_equal :expected_extension, Paperclip::Interpolations.extension(attachment, 4)
end
should "return the #to_param of the attachment" do
it "return the #to_param of the attachment" do
attachment = mock
attachment.expects(:to_param).returns("23-awesome")
attachment.expects(:instance).returns(attachment)
assert_equal "23-awesome", Paperclip::Interpolations.param(attachment, :style)
end
should "return the id of the attachment" do
it "return the id of the attachment" do
attachment = mock
attachment.expects(:id).returns(23)
attachment.expects(:instance).returns(attachment)
assert_equal 23, Paperclip::Interpolations.id(attachment, :style)
end
should "return nil for attachments to new records" do
it "return nil for attachments to new records" do
attachment = mock
attachment.expects(:id).returns(nil)
attachment.expects(:instance).returns(attachment)
assert_nil Paperclip::Interpolations.id(attachment, :style)
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.expects(:id).returns(23)
attachment.expects(:instance).returns(attachment)
assert_equal "000/000/023", Paperclip::Interpolations.id_partition(attachment, :style)
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.expects(:id).returns("32fnj23oio2f")
attachment.expects(:instance).returns(attachment)
assert_equal "32f/nj2/3oi", Paperclip::Interpolations.id_partition(attachment, :style)
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.expects(:id).returns(nil)
attachment.expects(:instance).returns(attachment)
assert_nil Paperclip::Interpolations.id_partition(attachment, :style)
end
should "return the name of the attachment" do
it "return the name of the attachment" do
attachment = mock
attachment.expects(:name).returns("file")
assert_equal "files", Paperclip::Interpolations.attachment(attachment, :style)
end
should "return the style" do
it "return the style" do
assert_equal :style, Paperclip::Interpolations.style(:attachment, :style)
end
should "return the default style" do
it "return the default style" do
attachment = mock
attachment.expects(:default_style).returns(:default_style)
assert_equal :default_style, Paperclip::Interpolations.style(attachment, nil)
end
should "reinterpolate :url" do
it "reinterpolate :url" do
attachment = mock
attachment.expects(:url).with(:style, :timestamp => false, :escape => false).returns("1234")
assert_equal "1234", Paperclip::Interpolations.url(attachment, :style)
end
should "raise if infinite loop detcted reinterpolating :url" do
it "raise if infinite loop detcted reinterpolating :url" do
attachment = Object.new
class << attachment
def url(*args)
......@@ -170,35 +170,35 @@ class InterpolationsTest < Test::Unit::TestCase
assert_raises(Paperclip::Errors::InfiniteInterpolationError){ Paperclip::Interpolations.url(attachment, :style) }
end
should "return the filename as basename.extension" do
it "return the filename as basename.extension" do
attachment = mock
attachment.expects(:styles).returns({})
attachment.expects(:original_filename).returns("one.jpg").times(3)
assert_equal "one.jpg", Paperclip::Interpolations.filename(attachment, :style)
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.expects(:styles).returns({:style => {:format => :png}})
attachment.expects(:original_filename).returns("one.jpg").times(2)
assert_equal "one.png", Paperclip::Interpolations.filename(attachment, :style)
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.stubs(:styles).returns({})
attachment.stubs(:original_filename).returns("one")
assert_equal "one", Paperclip::Interpolations.filename(attachment, :style)
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.stubs(:styles).returns({})
attachment.stubs(:original_filename).returns("one.ab)")
assert_equal "one", Paperclip::Interpolations.basename(attachment, :style)
end
should "return the timestamp" do
it "return the timestamp" do
now = Time.now
zone = 'UTC'
attachment = mock
......@@ -207,28 +207,28 @@ class InterpolationsTest < Test::Unit::TestCase
assert_equal now.in_time_zone(zone).to_s, Paperclip::Interpolations.timestamp(attachment, :style)
end
should "return updated_at" do
it "return updated_at" do
attachment = mock
seconds_since_epoch = 1234567890
attachment.expects(:updated_at).returns(seconds_since_epoch)
assert_equal seconds_since_epoch, Paperclip::Interpolations.updated_at(attachment, :style)
end
should "return attachment's hash when passing both arguments" do
it "return attachment's hash when passing both arguments" do
attachment = mock
fake_hash = "a_wicked_secure_hash"
attachment.expects(:hash_key).returns(fake_hash)
assert_equal fake_hash, Paperclip::Interpolations.hash(attachment, :style)
end
should "return Object#hash when passing no argument" do
it "return Object#hash when passing no argument" do
attachment = mock
fake_hash = "a_wicked_secure_hash"
attachment.expects(:hash_key).never.returns(fake_hash)
assert_not_equal fake_hash, Paperclip::Interpolations.hash
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(:attachment).with(:attachment, :style).returns("attachments")
Paperclip::Interpolations.expects(:notreal).never
......
require './test/helper'
require 'spec_helper'
class AbstractAdapterTest < Test::Unit::TestCase
describe Paperclip::AbstractAdapter do
class TestAdapter < Paperclip::AbstractAdapter
attr_accessor :tempfile
......@@ -10,31 +10,31 @@ class AbstractAdapterTest < Test::Unit::TestCase
end
context "content type from file command" do
setup do
before do
@adapter = TestAdapter.new
@adapter.stubs(:path).returns("image.png")
Paperclip.stubs(:run).returns("image/png\n")
end
should "return the content type without newline" do
it "return the content type without newline" do
assert_equal "image/png", @adapter.content_type
end
end
context "nil?" do
should "return false" do
it "return false" do
assert !TestAdapter.new.nil?
end
end
context "delegation" do
setup do
before do
@adapter = TestAdapter.new
@adapter.tempfile = stub("Tempfile")
end
[: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.public_send(method)
assert_received @adapter.tempfile, method
......@@ -42,18 +42,18 @@ class AbstractAdapterTest < Test::Unit::TestCase
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.original_filename = "awesome/file:name.png"
assert_equal "awesome_file_name.png", @adapter.original_filename
end
should 'be an assignment' do
it 'be an assignment' do
assert TestAdapter.new.assignment?
end
should 'not be nil' do
it 'not be nil' do
assert !TestAdapter.new.nil?
end
end
require './test/helper'
require 'pp'
require 'spec_helper'
class AttachmentAdapterTest < Test::Unit::TestCase
def setup
describe Paperclip::AttachmentAdapter do
before do
rebuild_model :path => "tmp/:class/:attachment/:style/:filename", :styles => {:thumb => '50x50'}
@attachment = Dummy.new.avatar
end
context "for an attachment" do
setup do
before do
@file = File.new(fixture_file("5k.png"))
@file.binmode
......@@ -18,37 +16,37 @@ class AttachmentAdapterTest < Test::Unit::TestCase
@subject = Paperclip.io_adapters.for(@attachment)
end
teardown do
after do
@file.close
@subject.close
end
should "get the right filename" do
it "get the right filename" do
assert_equal "5k.png", @subject.original_filename
end
should "force binmode on tempfile" do
it "force binmode on tempfile" do
assert @subject.instance_variable_get("@tempfile").binmode?
end
should "get the content type" do
it "get the content type" do
assert_equal "image/png", @subject.content_type
end
should "get the file's size" do
it "get the file's size" do
assert_equal 4456, @subject.size
end
should "return false for a call to nil?" do
it "return false for a call to nil?" do
assert ! @subject.nil?
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
assert_equal expected, @subject.fingerprint
end
should "read the contents of the file" do
it "read the contents of the file" do
expected = @file.read
actual = @subject.read
assert expected.length > 0
......@@ -59,7 +57,7 @@ class AttachmentAdapterTest < Test::Unit::TestCase
end
context "for a file with restricted characters in the name" do
setup do
before do
file_contents = IO.read(fixture_file("animated.gif"))
@file = StringIO.new(file_contents)
@file.stubs(:original_filename).returns('image:restricted.gif')
......@@ -70,21 +68,21 @@ class AttachmentAdapterTest < Test::Unit::TestCase
@subject = Paperclip.io_adapters.for(@attachment)
end
teardown do
after do
@subject.close
end
should "not generate paths that include restricted characters" do
assert_no_match(/:/, @subject.path)
it "not generate paths that include restricted characters" do
expect(@subject.path).to_not match(/:/)
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
end
end
context "for a style" do
setup do
before do
@file = File.new(fixture_file("5k.png"))
@file.binmode
......@@ -97,38 +95,38 @@ class AttachmentAdapterTest < Test::Unit::TestCase
@subject = Paperclip.io_adapters.for(@attachment.styles[:thumb])
end
teardown do
after do
@file.close
@thumb.close
@subject.close
end
should "get the original filename" do
it "get the original filename" do
assert_equal "5k.png", @subject.original_filename
end
should "force binmode on tempfile" do
it "force binmode on tempfile" do
assert @subject.instance_variable_get("@tempfile").binmode?
end
should "get the content type" do
it "get the content type" do
assert_equal "image/png", @subject.content_type
end
should "get the thumbnail's file size" do
it "get the thumbnail's file size" do
assert_equal @thumb.size, @subject.size
end
should "return false for a call to nil?" do
it "return false for a call to nil?" do
assert ! @subject.nil?
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
assert_equal expected, @subject.fingerprint
end
should "read the contents of the thumbnail" do
it "read the contents of the thumbnail" do
@thumb.rewind
expected = @thumb.read
actual = @subject.read
......
require './test/helper'
require 'spec_helper'
class DataUriAdapterTest < Test::Unit::TestCase
def teardown
describe Paperclip::DataUriAdapter do
after do
if @subject
@subject.close
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}")
assert_equal Paperclip::DataUriAdapter, adapter.class
end
context "a new instance" do
setup do
before do
@contents = "data:image/png;base64,#{original_base64_content}"
@subject = Paperclip.io_adapters.for(@contents)
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
end
should "return a content type" do
it "return a content type" do
assert_equal "image/png", @subject.content_type
end
should "return the size of the data" do
it "return the size of the data" do
assert_equal 4456, @subject.size
end
should "generate a correct MD5 hash of the contents" do
it "generate a correct MD5 hash of the contents" do
assert_equal(
Digest::MD5.hexdigest(Base64.decode64(original_base64_content)),
@subject.fingerprint
)
end
should "generate correct fingerprint after read" do
it "generate correct fingerprint after read" do
fingerprint = Digest::MD5.hexdigest(@subject.read)
assert_equal fingerprint, @subject.fingerprint
end
should "generate same fingerprint" do
it "generate same fingerprint" do
assert_equal @subject.fingerprint, @subject.fingerprint
end
should 'accept a content_type' do
it 'accept a content_type' do
@subject.content_type = 'image/png'
assert_equal 'image/png', @subject.content_type
end
should 'accept an original_filename' do
it 'accept an original_filename' do
@subject.original_filename = 'image.png'
assert_equal 'image.png', @subject.original_filename
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'
assert_equal 'image_restricted.png', @subject.original_filename
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'
assert_no_match /:/, @subject.path
expect(@subject.path).to_not match(/:/)
end
end
......
require './test/helper'
class EmptyStringAdapterTest < Test::Unit::TestCase
require 'spec_helper'
describe Paperclip::EmptyStringAdapter do
context 'a new instance' do
setup do
before do
@subject = Paperclip.io_adapters.for('')
end
should "return false for a call to nil?" do
it "return false for a call to nil?" do
assert !@subject.nil?
end
should 'return false for a call to assignment?' do
it 'return false for a call to assignment?' do
assert !@subject.assignment?
end
end
......
require './test/helper'
require 'spec_helper'
class FileAdapterTest < Test::Unit::TestCase
describe Paperclip::FileAdapter do
context "a new instance" do
context "with normal file" do
setup do
before do
@file = File.new(fixture_file("5k.png"))
@file.binmode
end
teardown do
after do
@file.close
@subject.close if @subject
end
context 'doing normal things' do
setup do
before do
@subject = Paperclip.io_adapters.for(@file)
end
should "get the right filename" do
it "get the right filename" do
assert_equal "5k.png", @subject.original_filename
end
should "force binmode on tempfile" do
it "force binmode on tempfile" do
assert @subject.instance_variable_get("@tempfile").binmode?
end
should "get the content type" do
it "get the content type" do
assert_equal "image/png", @subject.content_type
end
should "return content type as a string" do
assert_kind_of String, @subject.content_type
it "return content type as a string" do
expect(@subject.content_type).to be_a String
end
should "get the file's size" do
it "get the file's size" do
assert_equal 4456, @subject.size
end
should "return false for a call to nil?" do
it "return false for a call to nil?" do
assert ! @subject.nil?
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
assert_equal expected, @subject.fingerprint
end
should "read the contents of the file" do
it "read the contents of the file" do
expected = @file.read
assert expected.length > 0
assert_equal expected, @subject.read
......@@ -55,35 +55,35 @@ class FileAdapterTest < Test::Unit::TestCase
end
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')])
@subject = Paperclip.io_adapters.for(@file)
end
should "prefer officially registered mime type" do
it "prefer officially registered mime type" do
assert_equal "image/png", @subject.content_type
end
should "return content type as a string" do
assert_kind_of String, @subject.content_type
it "return content type as a string" do
expect(@subject.content_type).to be_a String
end
end
context "file with content type derived from file command on *nix" do
setup do
before do
MIME::Types.stubs(:type_for).returns([])
Paperclip.stubs(:run).returns("application/vnd.ms-office\n")
@subject = Paperclip.io_adapters.for(@file)
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
end
end
end
context "filename with restricted characters" do
setup do
before do
@file = File.open(fixture_file("animated.gif")) do |file|
StringIO.new(file.read)
end
......@@ -91,32 +91,32 @@ class FileAdapterTest < Test::Unit::TestCase
@subject = Paperclip.io_adapters.for(@file)
end
teardown do
after do
@file.close
@subject.close
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
end
should "not generate paths that include restricted characters" do
assert_no_match /:/, @subject.path
it "not generate paths that include restricted characters" do
expect(@subject.path).to_not match(/:/)
end
end
context "empty file" do
setup do
before do
@file = Tempfile.new("file_adapter_test")
@subject = Paperclip.io_adapters.for(@file)
end
teardown do
after do
@file.close
@subject.close
end
should "provide correct mime-type" do
it "provide correct mime-type" do
assert_match %r{.*/x-empty}, @subject.content_type
end
end
......
require './test/helper'
require 'spec_helper'
class HttpUrlProxyAdapterTest < Test::Unit::TestCase
describe Paperclip::HttpUrlProxyAdapter do
context "a new instance" do
setup do
before do
@open_return = StringIO.new("xxx")
@open_return.stubs(:content_type).returns("image/png")
Paperclip::HttpUrlProxyAdapter.any_instance.stubs(:download_content).returns(@open_return)
......@@ -10,78 +10,78 @@ class HttpUrlProxyAdapterTest < Test::Unit::TestCase
@subject = Paperclip.io_adapters.for(@url)
end
teardown do
after do
@subject.close
end
should "return a file name" do
it "return a file name" do
assert_equal "thoughtbot-logo.png", @subject.original_filename
end
should 'close open handle after reading' do
it 'close open handle after reading' do
assert_equal true, @open_return.closed?
end
should "return a content type" do
it "return a content type" do
assert_equal "image/png", @subject.content_type
end
should "return the size of the data" do
it "return the size of the data" do
assert_equal @open_return.size, @subject.size
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
end
should "generate correct fingerprint after read" do
it "generate correct fingerprint after read" do
fingerprint = Digest::MD5.hexdigest(@subject.read)
assert_equal fingerprint, @subject.fingerprint
end
should "generate same fingerprint" do
it "generate same fingerprint" do
assert_equal @subject.fingerprint, @subject.fingerprint
end
should "return the data contained in the StringIO" do
it "return the data contained in the StringIO" do
assert_equal "xxx", @subject.read
end
should 'accept a content_type' do
it 'accept a content_type' do
@subject.content_type = 'image/png'
assert_equal 'image/png', @subject.content_type
end
should 'accept an original_filename' do
it 'accept an original_filename' do
@subject.original_filename = 'image.png'
assert_equal 'image.png', @subject.original_filename
end
end
context "a url with query params" do
setup do
before do
Paperclip::HttpUrlProxyAdapter.any_instance.stubs(:download_content).returns(StringIO.new("x"))
@url = "https://github.com/thoughtbot/paperclip?file=test"
@subject = Paperclip.io_adapters.for(@url)
end
teardown do
after do
@subject.close
end
should "return a file name" do
it "return a file name" do
assert_equal "paperclip", @subject.original_filename
end
end
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"))
@url = "https://github.com/thoughtbot/paper:clip.jpg"
@subject = Paperclip.io_adapters.for(@url)
end
teardown do
after do
begin
@subject.close
rescue Exception
......@@ -89,12 +89,12 @@ class HttpUrlProxyAdapterTest < Test::Unit::TestCase
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
end
should "not generate paths that include restricted characters" do
assert_no_match(/:/, @subject.path)
it "not generate paths that include restricted characters" do
expect(@subject.path).to_not match(/:/)
end
end
......
require './test/helper'
require 'spec_helper'
class IdentityAdapterTest < Test::Unit::TestCase
should "respond to #new by returning the argument" do
describe Paperclip::IdentityAdapter do
it "respond to #new by returning the argument" do
adapter = Paperclip::IdentityAdapter.new
assert_equal :target, adapter.new(:target)
end
......
require './test/helper'
require 'spec_helper'
class NilAdapterTest < Test::Unit::TestCase
describe Paperclip::NilAdapter do
context 'a new instance' do
setup do
before do
@subject = Paperclip.io_adapters.for(nil)
end
should "get the right filename" do
it "get the right filename" do
assert_equal "", @subject.original_filename
end
should "get the content type" do
it "get the content type" do
assert_equal "", @subject.content_type
end
should "get the file's size" do
it "get the file's size" do
assert_equal 0, @subject.size
end
should "return true for a call to nil?" do
it "return true for a call to nil?" do
assert @subject.nil?
end
end
......
require './test/helper'
require 'spec_helper'
class AdapterRegistryTest < Test::Unit::TestCase
describe Paperclip::AttachmentRegistry do
context "for" do
setup do
before do
class AdapterTest
def initialize(target); end
end
@subject = Paperclip::AdapterRegistry.new
@subject.register(AdapterTest){|t| Symbol === t }
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
end
end
context "registered?" do
setup do
before do
class AdapterTest
def initialize(target); end
end
@subject = Paperclip::AdapterRegistry.new
@subject.register(AdapterTest){|t| Symbol === t }
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))
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)
end
end
......
require './test/helper'
require 'spec_helper'
class StringioFileProxyTest < Test::Unit::TestCase
describe Paperclip::StringioAdapter do
context "a new instance" do
setup do
before do
@contents = "abc123"
@stringio = StringIO.new(@contents)
@subject = Paperclip.io_adapters.for(@stringio)
end
should "return a file name" do
it "return a file name" do
assert_equal "data.txt", @subject.original_filename
end
should "return a content type" do
it "return a content type" do
assert_equal "text/plain", @subject.content_type
end
should "return the size of the data" do
it "return the size of the data" do
assert_equal 6, @subject.size
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
end
should "generate correct fingerprint after read" do
it "generate correct fingerprint after read" do
fingerprint = Digest::MD5.hexdigest(@subject.read)
assert_equal fingerprint, @subject.fingerprint
end
should "generate same fingerprint" do
it "generate same fingerprint" do
assert_equal @subject.fingerprint, @subject.fingerprint
end
should "return the data contained in the StringIO" do
it "return the data contained in the StringIO" do
assert_equal "abc123", @subject.read
end
should 'accept a content_type' do
it 'accept a content_type' do
@subject.content_type = 'image/png'
assert_equal 'image/png', @subject.content_type
end
should 'accept an original_filename' do
it 'accept an original_filename' do
@subject.original_filename = 'image.png'
assert_equal 'image.png', @subject.original_filename
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'
assert_equal 'image_restricted.png', @subject.original_filename
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'
assert_no_match /:/, @subject.path
expect(@subject.path).to_not match(/:/)
end
end
......
require './test/helper'
require 'spec_helper'
class UploadedFileAdapterTest < Test::Unit::TestCase
describe Paperclip::UploadedFileAdapter do
context "a new instance" do
context "with UploadedFile responding to #tempfile" do
setup do
before do
Paperclip::UploadedFileAdapter.content_type_detector = nil
class UploadedFile < OpenStruct; end
......@@ -20,32 +20,32 @@ class UploadedFileAdapterTest < Test::Unit::TestCase
@subject = Paperclip.io_adapters.for(@file)
end
should "get the right filename" do
it "get the right filename" do
assert_equal "5k.png", @subject.original_filename
end
should "force binmode on tempfile" do
it "force binmode on tempfile" do
assert @subject.instance_variable_get("@tempfile").binmode?
end
should "get the content type" do
it "get the content type" do
assert_equal "image/x-png-by-browser", @subject.content_type
end
should "get the file's size" do
it "get the file's size" do
assert_equal 4456, @subject.size
end
should "return false for a call to nil?" do
it "return false for a call to nil?" do
assert ! @subject.nil?
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
assert_equal expected, @subject.fingerprint
end
should "read the contents of the file" do
it "read the contents of the file" do
expected = @file.tempfile.read
assert expected.length > 0
assert_equal expected, @subject.read
......@@ -53,7 +53,7 @@ class UploadedFileAdapterTest < Test::Unit::TestCase
end
context "with UploadedFile that has restricted characters" do
setup do
before do
Paperclip::UploadedFileAdapter.content_type_detector = nil
class UploadedFile < OpenStruct; end
......@@ -66,17 +66,17 @@ class UploadedFileAdapterTest < Test::Unit::TestCase
@subject = Paperclip.io_adapters.for(@file)
end
should "not generate paths that include restricted characters" do
assert_no_match /:/, @subject.path
it "not generate paths that include restricted characters" do
expect(@subject.path).to_not match(/:/)
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
end
end
context "with UploadFile responding to #path" do
setup do
before do
Paperclip::UploadedFileAdapter.content_type_detector = nil
class UploadedFile < OpenStruct; end
......@@ -89,32 +89,32 @@ class UploadedFileAdapterTest < Test::Unit::TestCase
@subject = Paperclip.io_adapters.for(@file)
end
should "get the right filename" do
it "get the right filename" do
assert_equal "5k.png", @subject.original_filename
end
should "force binmode on tempfile" do
it "force binmode on tempfile" do
assert @subject.instance_variable_get("@tempfile").binmode?
end
should "get the content type" do
it "get the content type" do
assert_equal "image/x-png-by-browser", @subject.content_type
end
should "get the file's size" do
it "get the file's size" do
assert_equal 4456, @subject.size
end
should "return false for a call to nil?" do
it "return false for a call to nil?" do
assert ! @subject.nil?
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
assert_equal expected, @subject.fingerprint
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.binmode
expected = expected_file.read
......@@ -123,7 +123,7 @@ class UploadedFileAdapterTest < Test::Unit::TestCase
end
context "don't trust client-given MIME type" do
setup do
before do
Paperclip::UploadedFileAdapter.content_type_detector =
Paperclip::FileCommandContentTypeDetector
......@@ -137,7 +137,7 @@ class UploadedFileAdapterTest < Test::Unit::TestCase
@subject = Paperclip.io_adapters.for(@file)
end
should "get the content type" do
it "get the content type" do
assert_equal "image/png", @subject.content_type
end
end
......
require './test/helper'
require 'spec_helper'
class UriProxyTest < Test::Unit::TestCase
describe Paperclip::UriAdapter do
context "a new instance" do
setup do
before do
@open_return = StringIO.new("xxx")
@open_return.stubs(:content_type).returns("image/png")
Paperclip::UriAdapter.any_instance.stubs(:download_content).returns(@open_return)
......@@ -10,45 +10,45 @@ class UriProxyTest < Test::Unit::TestCase
@subject = Paperclip.io_adapters.for(@uri)
end
should "return a file name" do
it "return a file name" do
assert_equal "thoughtbot-logo.png", @subject.original_filename
end
should 'close open handle after reading' do
it 'close open handle after reading' do
assert_equal true, @open_return.closed?
end
should "return a content type" do
it "return a content type" do
assert_equal "image/png", @subject.content_type
end
should "return the size of the data" do
it "return the size of the data" do
assert_equal @open_return.size, @subject.size
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
end
should "generate correct fingerprint after read" do
it "generate correct fingerprint after read" do
fingerprint = Digest::MD5.hexdigest(@subject.read)
assert_equal fingerprint, @subject.fingerprint
end
should "generate same fingerprint" do
it "generate same fingerprint" do
assert_equal @subject.fingerprint, @subject.fingerprint
end
should "return the data contained in the StringIO" do
it "return the data contained in the StringIO" do
assert_equal "xxx", @subject.read
end
should 'accept a content_type' do
it 'accept a content_type' do
@subject.content_type = 'image/png'
assert_equal 'image/png', @subject.content_type
end
should 'accept an orgiginal_filename' do
it 'accept an orgiginal_filename' do
@subject.original_filename = 'image.png'
assert_equal 'image.png', @subject.original_filename
end
......@@ -56,46 +56,46 @@ class UriProxyTest < Test::Unit::TestCase
end
context "a directory index url" do
setup do
before do
Paperclip::UriAdapter.any_instance.stubs(:download_content).returns(StringIO.new("xxx"))
@uri = URI.parse("http://thoughtbot.com")
@subject = Paperclip.io_adapters.for(@uri)
end
should "return a file name" do
it "return a file name" do
assert_equal "index.html", @subject.original_filename
end
should "return a content type" do
it "return a content type" do
assert_equal "text/html", @subject.content_type
end
end
context "a url with query params" do
setup do
before do
Paperclip::UriAdapter.any_instance.stubs(:download_content).returns(StringIO.new("xxx"))
@uri = URI.parse("https://github.com/thoughtbot/paperclip?file=test")
@subject = Paperclip.io_adapters.for(@uri)
end
should "return a file name" do
it "return a file name" do
assert_equal "paperclip", @subject.original_filename
end
end
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"))
@uri = URI.parse("https://github.com/thoughtbot/paper:clip.jpg")
@subject = Paperclip.io_adapters.for(@uri)
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
end
should "not generate paths that include restricted characters" do
assert_no_match /:/, @subject.path
it "not generate paths that include restricted characters" do
expect(@subject.path).to_not match(/:/)
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
setup do
before do
reset_table("dummies") do |d|
d.string :title
d.string :avatar_file_name
......@@ -21,7 +24,7 @@ class ValidateAttachmentContentTypeMatcherTest < Test::Unit::TestCase
end
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/.*}
end
......@@ -29,7 +32,7 @@ class ValidateAttachmentContentTypeMatcherTest < Test::Unit::TestCase
end
context "given a class with a matching validation" do
setup do
before do
Dummy.validates_attachment_content_type :avatar, :content_type => %r{image/.*}
end
......@@ -37,7 +40,7 @@ class ValidateAttachmentContentTypeMatcherTest < Test::Unit::TestCase
end
context "given a class with other validations but matching types" do
setup do
before do
Dummy.validates_presence_of :title
Dummy.validates_attachment_content_type :avatar, :content_type => %r{image/.*}
end
......@@ -46,7 +49,7 @@ class ValidateAttachmentContentTypeMatcherTest < Test::Unit::TestCase
end
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/.*}
@matcher = self.class.validate_attachment_content_type(:avatar).
allowing(%w(image/png image/jpeg))
......@@ -56,7 +59,7 @@ class ValidateAttachmentContentTypeMatcherTest < Test::Unit::TestCase
end
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/.*}
@matcher = self.class.validate_attachment_content_type(:avatar).
allowing(%w(image/png image/jpeg))
......@@ -66,7 +69,7 @@ class ValidateAttachmentContentTypeMatcherTest < Test::Unit::TestCase
end
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/.*}
@matcher = self.class.validate_attachment_content_type(:avatar).
rejecting(%w(audio/mp3 application/octet-stream))
......@@ -76,7 +79,7 @@ class ValidateAttachmentContentTypeMatcherTest < Test::Unit::TestCase
end
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/.*}
@matcher = self.class.validate_attachment_content_type(:avatar).
rejecting(%w(audio/mp3 application/octet-stream))
......@@ -86,7 +89,7 @@ class ValidateAttachmentContentTypeMatcherTest < Test::Unit::TestCase
end
context "using an :if to control the validation" do
setup do
before do
Dummy.class_eval do
validates_attachment_content_type :avatar, :content_type => %r{image/*} , :if => :go
attr_accessor :go
......@@ -97,14 +100,14 @@ class ValidateAttachmentContentTypeMatcherTest < Test::Unit::TestCase
@dummy = Dummy.new
end
should "run the validation if the control is true" do
it "run the validation if the control is true" do
@dummy.go = true
assert_accepts @matcher, @dummy
expect(@matcher).to accept(@dummy)
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
assert_rejects @matcher, @dummy
expect(@matcher).to_not accept(@dummy)
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
setup do
before do
reset_table("dummies") do |d|
d.string :avatar_file_name
end
......@@ -17,7 +20,7 @@ class ValidateAttachmentPresenceMatcherTest < Test::Unit::TestCase
end
context "given a class with a matching validation" do
setup do
before do
Dummy.validates_attachment_presence :avatar
end
......@@ -25,7 +28,7 @@ class ValidateAttachmentPresenceMatcherTest < Test::Unit::TestCase
end
context "given an instance with other attachment validations" do
setup do
before do
reset_table("dummies") do |d|
d.string :avatar_file_name
d.string :avatar_content_type
......@@ -40,14 +43,14 @@ class ValidateAttachmentPresenceMatcherTest < Test::Unit::TestCase
@matcher = self.class.validate_attachment_presence(:avatar)
end
should "it should validate properly" do
it "it should validate properly" do
@dummy.avatar = File.new fixture_file('5k.png')
assert_accepts @matcher, @dummy
expect(@matcher).to accept(@dummy)
end
end
context "using an :if to control the validation" do
setup do
before do
Dummy.class_eval do
validates_attachment_presence :avatar, :if => :go
attr_accessor :go
......@@ -56,14 +59,14 @@ class ValidateAttachmentPresenceMatcherTest < Test::Unit::TestCase
@dummy.avatar = nil
end
should "run the validation if the control is true" do
it "run the validation if the control is true" do
@dummy.go = true
assert_accepts @matcher, @dummy
expect(@matcher).to accept(@dummy)
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
assert_rejects @matcher, @dummy
expect(@matcher).to_not accept(@dummy)
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
setup do
before do
reset_table("dummies") do |d|
d.string :avatar_file_name
d.integer :avatar_file_size
......@@ -13,44 +16,48 @@ class ValidateAttachmentSizeMatcherTest < Test::Unit::TestCase
end
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
should_reject_dummy_class
end
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
end
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
end
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
end
end
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
setup { Dummy.validates_attachment_size :avatar, :less_than => 1 }
before { Dummy.validates_attachment_size :avatar, :less_than => 1 }
should_accept_dummy_class
end
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
end
end
context "using an :if to control the validation" do
setup do
before do
Dummy.class_eval do
validates_attachment_size :avatar, :greater_than => 1024, :if => :go
attr_accessor :go
......@@ -59,28 +66,28 @@ class ValidateAttachmentSizeMatcherTest < Test::Unit::TestCase
@matcher = self.class.validate_attachment_size(:avatar).greater_than(1024)
end
should "run the validation if the control is true" do
it "run the validation if the control is true" do
@dummy.go = true
assert_accepts @matcher, @dummy
expect(@matcher).to accept(@dummy)
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
assert_rejects @matcher, @dummy
expect(@matcher).to_not accept(@dummy)
end
end
context "post processing" do
setup do
before do
Dummy.validates_attachment_size :avatar, :greater_than => 1024
@dummy = Dummy.new
@matcher = self.class.validate_attachment_size(:avatar).greater_than(1024)
end
should "be skipped" do
it "be skipped" do
@dummy.avatar.expects(:post_process).never
assert_accepts @matcher, @dummy
expect(@matcher).to accept(@dummy)
end
end
end
......
require './test/helper'
require 'spec_helper'
class MediaTypeSpoofDetectorTest < Test::Unit::TestCase
should 'reject a file that is named .html and identifies as PNG' do
describe Paperclip::MediaTypeSpoofDetector do
it 'reject a file that is named .html and identifies as PNG' do
file = File.open(fixture_file("5k.png"))
assert Paperclip::MediaTypeSpoofDetector.using(file, "5k.html").spoofed?
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"))
assert ! Paperclip::MediaTypeSpoofDetector.using(file, "5k.jpg").spoofed?
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"))
assert ! Paperclip::MediaTypeSpoofDetector.using(file, "empty.html").spoofed?
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"))
assert ! Paperclip::MediaTypeSpoofDetector.using(file, "").spoofed?
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")))
assert ! Paperclip::MediaTypeSpoofDetector.using(adapter, adapter.original_filename).spoofed?
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
Paperclip.options[:content_type_mappings] = { pem: "text/plain" }
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
setup do
rebuild_model
@file = File.new(fixture_file("5k.png"), 'rb')
before do
rebuild_model("Dummy")
reset_class("Dummy")
end
teardown { @file.close }
should "be able to use Paperclip like a normal class" do
reset_class("Dummy")
it "be able to use Paperclip like a normal class" do
@dummy = Dummy.new
assert_nothing_raised do
......@@ -18,13 +15,12 @@ class MetaClassTest < Test::Unit::TestCase
end
end
should "work like any other instance" do
reset_class("Dummy")
it "work like any other instance" do
@dummy = Dummy.new
rebuild_meta_class_of(@dummy)
assert_nothing_raised do
@dummy.avatar = @file
@dummy.avatar = File.new(fixture_file("5k.png"), 'rb')
end
assert @dummy.save
end
......
require './test/helper'
require 'spec_helper'
class PaperclipMissingAttachmentStylesTest < Test::Unit::TestCase
def setup
describe 'Missing Attachment Styles' do
before do
Paperclip::AttachmentRegistry.clear
end
context "Paperclip" do
setup do
Paperclip::AttachmentRegistry.clear
end
teardown do
File.unlink(Paperclip.registered_attachments_styles_path) rescue nil
end
should "enable to get and set path to registered styles file" do
assert_equal ROOT.join('tmp/public/system/paperclip_attachments.yml').to_s, Paperclip.registered_attachments_styles_path
Paperclip.registered_attachments_styles_path = '/tmp/config/paperclip_attachments.yml'
assert_equal '/tmp/config/paperclip_attachments.yml', Paperclip.registered_attachments_styles_path
Paperclip.registered_attachments_styles_path = nil
assert_equal ROOT.join('tmp/public/system/paperclip_attachments.yml').to_s, Paperclip.registered_attachments_styles_path
end
after do
File.unlink(Paperclip.registered_attachments_styles_path) rescue nil
end
should "be able to get current attachment styles" do
assert_equal Hash.new, Paperclip.send(:current_attachments_styles)
rebuild_model :styles => {:croppable => '600x600>', :big => '1000x1000>'}
expected_hash = { :Dummy => {:avatar => [:big, :croppable]}}
assert_equal expected_hash, Paperclip.send(:current_attachments_styles)
end
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
Paperclip.registered_attachments_styles_path = '/tmp/config/paperclip_attachments.yml'
assert_equal '/tmp/config/paperclip_attachments.yml', Paperclip.registered_attachments_styles_path
Paperclip.registered_attachments_styles_path = nil
assert_equal ROOT.join('tmp/public/system/paperclip_attachments.yml').to_s, Paperclip.registered_attachments_styles_path
end
should "be able to save current attachment styles for further comparison" do
rebuild_model :styles => {:croppable => '600x600>', :big => '1000x1000>'}
Paperclip.save_current_attachments_styles!
expected_hash = { :Dummy => {:avatar => [:big, :croppable]}}
assert_equal expected_hash, YAML.load_file(Paperclip.registered_attachments_styles_path)
end
it "be able to get current attachment styles" do
assert_equal Hash.new, Paperclip.send(:current_attachments_styles)
rebuild_model :styles => {:croppable => '600x600>', :big => '1000x1000>'}
expected_hash = { :Dummy => {:avatar => [:big, :croppable]}}
assert_equal expected_hash, Paperclip.send(:current_attachments_styles)
end
should "be able to read registered attachment styles from file" do
rebuild_model :styles => {:croppable => '600x600>', :big => '1000x1000>'}
Paperclip.save_current_attachments_styles!
expected_hash = { :Dummy => {:avatar => [:big, :croppable]}}
assert_equal expected_hash, Paperclip.send(:get_registered_attachments_styles)
end
it "be able to save current attachment styles for further comparison" do
rebuild_model :styles => {:croppable => '600x600>', :big => '1000x1000>'}
Paperclip.save_current_attachments_styles!
expected_hash = { :Dummy => {:avatar => [:big, :croppable]}}
assert_equal expected_hash, YAML.load_file(Paperclip.registered_attachments_styles_path)
end
should "be able to calculate differences between registered styles and current styles" do
rebuild_model :styles => {:croppable => '600x600>', :big => '1000x1000>'}
Paperclip.save_current_attachments_styles!
rebuild_model :styles => {:thumb => 'x100', :export => 'x400>', :croppable => '600x600>', :big => '1000x1000>'}
expected_hash = { :Dummy => {:avatar => [:export, :thumb]} }
assert_equal expected_hash, Paperclip.missing_attachments_styles
it "be able to read registered attachment styles from file" do
rebuild_model :styles => {:croppable => '600x600>', :big => '1000x1000>'}
Paperclip.save_current_attachments_styles!
expected_hash = { :Dummy => {:avatar => [:big, :croppable]}}
assert_equal expected_hash, Paperclip.send(:get_registered_attachments_styles)
end
ActiveRecord::Base.connection.create_table :books, :force => true
class ::Book < ActiveRecord::Base
has_attached_file :cover, :styles => {:small => 'x100', :large => '1000x1000>'}
has_attached_file :sample, :styles => {:thumb => 'x100'}
end
it "be able to calculate differences between registered styles and current styles" do
rebuild_model :styles => {:croppable => '600x600>', :big => '1000x1000>'}
Paperclip.save_current_attachments_styles!
rebuild_model :styles => {:thumb => 'x100', :export => 'x400>', :croppable => '600x600>', :big => '1000x1000>'}
expected_hash = { :Dummy => {:avatar => [:export, :thumb]} }
assert_equal expected_hash, Paperclip.missing_attachments_styles
expected_hash = {
:Dummy => {:avatar => [:export, :thumb]},
:Book => {:sample => [:thumb], :cover => [:large, :small]}
}
assert_equal expected_hash, Paperclip.missing_attachments_styles
Paperclip.save_current_attachments_styles!
assert_equal Hash.new, Paperclip.missing_attachments_styles
ActiveRecord::Base.connection.create_table :books, :force => true
class ::Book < ActiveRecord::Base
has_attached_file :cover, :styles => {:small => 'x100', :large => '1000x1000>'}
has_attached_file :sample, :styles => {:thumb => 'x100'}
end
should "be able to calculate differences when a new attachment is added to a model" do
rebuild_model :styles => {:croppable => '600x600>', :big => '1000x1000>'}
Paperclip.save_current_attachments_styles!
expected_hash = {
:Dummy => {:avatar => [:export, :thumb]},
:Book => {:sample => [:thumb], :cover => [:large, :small]}
}
assert_equal expected_hash, Paperclip.missing_attachments_styles
Paperclip.save_current_attachments_styles!
assert_equal Hash.new, Paperclip.missing_attachments_styles
end
class ::Dummy
has_attached_file :photo, :styles => {:small => 'x100', :large => '1000x1000>'}
end
it "be able to calculate differences when a new attachment is added to a model" do
rebuild_model :styles => {:croppable => '600x600>', :big => '1000x1000>'}
Paperclip.save_current_attachments_styles!
expected_hash = {
:Dummy => {:photo => [:large, :small]}
}
assert_equal expected_hash, Paperclip.missing_attachments_styles
Paperclip.save_current_attachments_styles!
assert_equal Hash.new, Paperclip.missing_attachments_styles
class ::Dummy
has_attached_file :photo, :styles => {:small => 'x100', :large => '1000x1000>'}
end
# It's impossible to build styles hash without loading from database whole bunch of records
should "skip lambda-styles" do
rebuild_model :styles => lambda{ |attachment| attachment.instance.other == 'a' ? {:thumb => "50x50#"} : {:large => "400x400"} }
assert_equal Hash.new, Paperclip.send(:current_attachments_styles)
end
expected_hash = {
:Dummy => {:photo => [:large, :small]}
}
assert_equal expected_hash, Paperclip.missing_attachments_styles
Paperclip.save_current_attachments_styles!
assert_equal Hash.new, Paperclip.missing_attachments_styles
end
# It's impossible to build styles hash without loading from database whole bunch of records
it "skip lambda-styles" do
rebuild_model :styles => lambda{ |attachment| attachment.instance.other == 'a' ? {:thumb => "50x50#"} : {:large => "400x400"} }
assert_equal Hash.new, Paperclip.send(:current_attachments_styles)
end
end
require './test/helper'
require 'spec_helper'
class PaperclipTest < Test::Unit::TestCase
context "Calling Paperclip.run" do
setup do
describe Paperclip do
context ".run" do
before do
Paperclip.options[:log_command] = false
Cocaine::CommandLine.expects(:new).with("convert", "stuff", {}).returns(stub(:run))
@original_command_line_path = Cocaine::CommandLine.path
end
teardown do
after do
Paperclip.options[:log_command] = true
Cocaine::CommandLine.path = @original_command_line_path
end
should "run the command with Cocaine" do
it "run the command with Cocaine" do
Paperclip.run("convert", "stuff")
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"
Paperclip.run("convert", "stuff")
assert_equal [Cocaine::CommandLine.path].flatten.include?("/opt/my_app/bin"), true
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.path = nil
Paperclip.options[:command_path] = "/opt/my_app/bin"
......@@ -33,7 +33,7 @@ class PaperclipTest < Test::Unit::TestCase
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
Cocaine::CommandLine.path = "/something/else"
100.times do |x|
......@@ -42,24 +42,24 @@ class PaperclipTest < Test::Unit::TestCase
end
context "Calling Paperclip.log without options[:logger] set" do
setup do
before do
Paperclip.logger = nil
Paperclip.options[:logger] = nil
end
teardown do
after do
Paperclip.options[:logger] = ActiveRecord::Base.logger
Paperclip.logger = ActiveRecord::Base.logger
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
Paperclip.log('something')
end
end
end
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
Cocaine::CommandLine.expects(:new).with("convert", "stuff", :logger => Paperclip.logger).returns(stub(:run))
Paperclip.run("convert", "stuff")
......@@ -67,7 +67,7 @@ class PaperclipTest < Test::Unit::TestCase
end
context "Paperclip.each_instance_with_attachment" do
setup do
before do
@file = File.new(fixture_file("5k.png"), 'rb')
d1 = Dummy.create(:avatar => @file)
d2 = Dummy.create
......@@ -75,47 +75,47 @@ class PaperclipTest < Test::Unit::TestCase
@expected = [d1, d3]
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 = []
Paperclip.each_instance_with_attachment("Dummy", "avatar") do |instance|
actual << instance
end
assert_same_elements @expected, actual
expect(actual).to match_array @expected
end
end
should "raise when sent #processor and the name of a class that doesn't exist" do
assert_raises(NameError){ Paperclip.processor(:boogey_man) }
it "raise when sent #processor and the name of a class that doesn't exist" do
assert_raises(LoadError){ Paperclip.processor(:boogey_man) }
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)
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
assert_equal ::One::Two, Paperclip.class_for("One::Two")
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 ::Four; end
assert_raise NameError do
assert_raises NameError do
Paperclip.class_for("Three::Four")
end
end
context "An ActiveRecord model with an 'avatar' attachment" do
setup do
before do
rebuild_model :path => "tmp/:class/omg/:style.:extension"
@file = File.new(fixture_file("5k.png"), 'rb')
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
Dummy.class_eval do
has_attached_file :blah
......@@ -125,14 +125,14 @@ class PaperclipTest < Test::Unit::TestCase
if using_protected_attributes?
context "that is attr_protected" do
setup do
before do
Dummy.class_eval do
attr_protected :avatar
end
@dummy = Dummy.new
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!",
:avatar => @file }
......@@ -140,7 +140,7 @@ class PaperclipTest < Test::Unit::TestCase
assert ! @dummy.avatar?
end
should "still allow assigment on normal set" do
it "still allow assigment on normal set" do
@dummy.other = "I'm set!"
@dummy.avatar = @file
......@@ -151,42 +151,42 @@ class PaperclipTest < Test::Unit::TestCase
end
context "with a subclass" do
setup do
before do
class ::SubDummy < Dummy; 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
@subdummy = SubDummy.create(:avatar => @file)
end
end
teardown do
after do
SubDummy.delete_all
Object.send(:remove_const, "SubDummy") rescue nil
end
end
should "have an #avatar method" do
it "have an avatar getter method" do
assert Dummy.new.respond_to?(:avatar)
end
should "have an #avatar= method" do
it "have an avatar setter method" do
assert Dummy.new.respond_to?(:avatar=)
end
context "that is valid" do
setup do
before do
@dummy = Dummy.new
@dummy.avatar = @file
end
should "be valid" do
it "be valid" do
assert @dummy.valid?
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
ActiveRecord::Base::Attachment
end
......@@ -194,7 +194,7 @@ class PaperclipTest < Test::Unit::TestCase
end
context "configuring a custom processor" do
setup do
before do
@freedom_processor = Class.new do
def make(file, options = {}, attachment = nil)
file
......@@ -206,11 +206,11 @@ class PaperclipTest < Test::Unit::TestCase
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)
end
teardown do
after do
Paperclip.clear_processors!
end
end
......
require './test/helper'
require 'spec_helper'
class PluralCacheTest < Test::Unit::TestCase
should 'cache pluralizations' do
describe 'Plural cache' do
it 'cache pluralizations' do
cache = Paperclip::Interpolations::PluralCache.new
word = "box"
......@@ -11,7 +11,7 @@ class PluralCacheTest < Test::Unit::TestCase
cache.pluralize(word)
end
should 'cache pluralizations and underscores' do
it 'cache pluralizations and underscores' do
cache = Paperclip::Interpolations::PluralCache.new
word = "BigBox"
......@@ -22,13 +22,13 @@ class PluralCacheTest < Test::Unit::TestCase
cache.underscore_and_pluralize(word)
end
should 'pluralize words' do
it 'pluralize words' do
cache = Paperclip::Interpolations::PluralCache.new
word = "box"
assert_equal "boxes", cache.pluralize(word)
end
should 'pluralize and underscore words' do
it 'pluralize and underscore words' do
cache = Paperclip::Interpolations::PluralCache.new
word = "BigBox"
assert_equal "big_boxes", cache.underscore_and_pluralize(word)
......
require './test/helper'
require 'spec_helper'
class ProcessorTest < Test::Unit::TestCase
should "instantiate and call #make when sent #make to the class" do
describe Paperclip::Processor do
it "instantiate and call #make when sent #make to the class" do
processor = mock
processor.expects(:make).with()
Paperclip::Processor.expects(:new).with(:one, :two, :three).returns(processor)
......@@ -9,7 +9,7 @@ class ProcessorTest < Test::Unit::TestCase
end
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
Cocaine::CommandLine.expects(:new).with("convert", "stuff", {}).returns(stub(:run))
Paperclip::Processor.new('filename').convert("stuff")
......@@ -17,7 +17,7 @@ class ProcessorTest < Test::Unit::TestCase
end
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
Cocaine::CommandLine.expects(:new).with("identify", "stuff", {}).returns(stub(:run))
Paperclip::Processor.new('filename').identify("stuff")
......
require './test/helper'
require 'spec_helper'
require 'rake'
load './lib/tasks/paperclip.rake'
class RakeTest < Test::Unit::TestCase
describe Rake do
context "calling `rake paperclip:refresh:thumbnails`" do
setup do
before do
rebuild_model
Paperclip::Task.stubs(:obtain_class).returns('Dummy')
@bogus_instance = Dummy.new
......@@ -16,22 +16,22 @@ class RakeTest < Test::Unit::TestCase
Paperclip.stubs(:each_instance_with_attachment).multiple_yields @bogus_instance, @valid_instance
end
context "when there is an exception in reprocess!" do
setup do
before do
@bogus_instance.avatar.stubs(:reprocess!).raises
end
should "catch the exception" do
it "catch the exception" do
assert_nothing_raised do
::Rake::Task['paperclip:refresh:thumbnails'].execute
end
end
should "continue to the next instance" do
it "continue to the next instance" do
@valid_instance.avatar.expects(:reprocess!)
::Rake::Task['paperclip:refresh:thumbnails'].execute
end
should "print the exception" do
it "print the exception" do
exception_msg = 'Some Exception'
@bogus_instance.avatar.stubs(:reprocess!).raises(exception_msg)
Paperclip::Task.expects(:log_error).with do |str|
......@@ -40,14 +40,14 @@ class RakeTest < Test::Unit::TestCase
::Rake::Task['paperclip:refresh:thumbnails'].execute
end
should "print the class name" do
it "print the class name" do
Paperclip::Task.expects(:log_error).with do |str|
str.match 'Dummy'
end
::Rake::Task['paperclip:refresh:thumbnails'].execute
end
should "print the instance ID" do
it "print the instance ID" do
Paperclip::Task.expects(:log_error).with do |str|
str.match "ID #{@bogus_instance.id}"
end
......@@ -56,19 +56,19 @@ class RakeTest < Test::Unit::TestCase
end
context "when there is an error in reprocess!" do
setup do
before do
@errors = mock('errors')
@errors.stubs(:full_messages).returns([''])
@errors.stubs(:blank?).returns(false)
@bogus_instance.stubs(:errors).returns(@errors)
end
should "continue to the next instance" do
it "continue to the next instance" do
@valid_instance.avatar.expects(:reprocess!)
::Rake::Task['paperclip:refresh:thumbnails'].execute
end
should "print the error" do
it "print the error" do
error_msg = 'Some Error'
@errors.stubs(:full_messages).returns([error_msg])
Paperclip::Task.expects(:log_error).with do |str|
......@@ -77,14 +77,14 @@ class RakeTest < Test::Unit::TestCase
::Rake::Task['paperclip:refresh:thumbnails'].execute
end
should "print the class name" do
it "print the class name" do
Paperclip::Task.expects(:log_error).with do |str|
str.match 'Dummy'
end
::Rake::Task['paperclip:refresh:thumbnails'].execute
end
should "print the instance ID" do
it "print the instance ID" do
Paperclip::Task.expects(:log_error).with do |str|
str.match "ID #{@bogus_instance.id}"
end
......@@ -94,7 +94,7 @@ class RakeTest < Test::Unit::TestCase
end
context "Paperclip::Task.log_error method" do
should "print its argument to STDERR" do
it "print its argument to STDERR" do
msg = 'Some Message'
$stderr.expects(:puts).with(msg)
Paperclip::Task.log_error(msg)
......
require './test/helper'
require 'spec_helper'
require 'paperclip/schema'
require 'active_support/testing/deprecation'
class SchemaTest < Test::Unit::TestCase
describe Paperclip::Schema do
include ActiveSupport::Testing::Deprecation
def setup
before do
rebuild_class
end
def teardown
after do
Dummy.connection.drop_table :dummies rescue nil
end
context "within table definition" do
context "using #has_attached_file" do
setup do
before do
ActiveSupport::Deprecation.silenced = false
end
should "create attachment columns" do
it "create attachment columns" do
Dummy.connection.create_table :dummies, :force => true do |t|
ActiveSupport::Deprecation.silence do
t.has_attached_file :avatar
......@@ -28,13 +28,13 @@ class SchemaTest < Test::Unit::TestCase
columns = Dummy.columns.map{ |column| [column.name, column.type] }
assert_includes columns, ['avatar_file_name', :string]
assert_includes columns, ['avatar_content_type', :string]
assert_includes columns, ['avatar_file_size', :integer]
assert_includes columns, ['avatar_updated_at', :datetime]
expect(columns).to include(['avatar_file_name', :string])
expect(columns).to include(['avatar_content_type', :string])
expect(columns).to include(['avatar_file_size', :integer])
expect(columns).to include(['avatar_updated_at', :datetime])
end
should "display deprecation warning" do
it "display deprecation warning" do
Dummy.connection.create_table :dummies, :force => true do |t|
assert_deprecated do
t.has_attached_file :avatar
......@@ -44,69 +44,69 @@ class SchemaTest < Test::Unit::TestCase
end
context "using #attachment" do
setup do
before do
Dummy.connection.create_table :dummies, :force => true do |t|
t.attachment :avatar
end
rebuild_class
end
should "create attachment columns" do
it "create attachment columns" do
columns = Dummy.columns.map{ |column| [column.name, column.type] }
assert_includes columns, ['avatar_file_name', :string]
assert_includes columns, ['avatar_content_type', :string]
assert_includes columns, ['avatar_file_size', :integer]
assert_includes columns, ['avatar_updated_at', :datetime]
expect(columns).to include(['avatar_file_name', :string])
expect(columns).to include(['avatar_content_type', :string])
expect(columns).to include(['avatar_file_size', :integer])
expect(columns).to include(['avatar_updated_at', :datetime])
end
end
end
context "within schema statement" do
setup do
before do
Dummy.connection.create_table :dummies, :force => true
end
context "migrating up" do
context "with single attachment" do
setup do
before do
Dummy.connection.add_attachment :dummies, :avatar
rebuild_class
end
should "create attachment columns" do
it "create attachment columns" do
columns = Dummy.columns.map{ |column| [column.name, column.type] }
assert_includes columns, ['avatar_file_name', :string]
assert_includes columns, ['avatar_content_type', :string]
assert_includes columns, ['avatar_file_size', :integer]
assert_includes columns, ['avatar_updated_at', :datetime]
expect(columns).to include(['avatar_file_name', :string])
expect(columns).to include(['avatar_content_type', :string])
expect(columns).to include(['avatar_file_size', :integer])
expect(columns).to include(['avatar_updated_at', :datetime])
end
end
context "with multiple attachments" do
setup do
before do
Dummy.connection.add_attachment :dummies, :avatar, :photo
rebuild_class
end
should "create attachment columns" do
it "create attachment columns" do
columns = Dummy.columns.map{ |column| [column.name, column.type] }
assert_includes columns, ['avatar_file_name', :string]
assert_includes columns, ['avatar_content_type', :string]
assert_includes columns, ['avatar_file_size', :integer]
assert_includes columns, ['avatar_updated_at', :datetime]
assert_includes columns, ['photo_file_name', :string]
assert_includes columns, ['photo_content_type', :string]
assert_includes columns, ['photo_file_size', :integer]
assert_includes columns, ['photo_updated_at', :datetime]
expect(columns).to include(['avatar_file_name', :string])
expect(columns).to include(['avatar_content_type', :string])
expect(columns).to include(['avatar_file_size', :integer])
expect(columns).to include(['avatar_updated_at', :datetime])
expect(columns).to include(['photo_file_name', :string])
expect(columns).to include(['photo_content_type', :string])
expect(columns).to include(['photo_file_size', :integer])
expect(columns).to include(['photo_updated_at', :datetime])
end
end
context "with no attachment" do
should "raise an error" do
assert_raise ArgumentError do
it "raise an error" do
assert_raises ArgumentError do
Dummy.connection.add_attachment :dummies
rebuild_class
end
......@@ -115,7 +115,7 @@ class SchemaTest < Test::Unit::TestCase
end
context "migrating down" do
setup do
before do
Dummy.connection.change_table :dummies do |t|
t.column :avatar_file_name, :string
t.column :avatar_content_type, :string
......@@ -125,10 +125,10 @@ class SchemaTest < Test::Unit::TestCase
end
context "using #drop_attached_file" do
setup do
before do
ActiveSupport::Deprecation.silenced = false
end
should "remove the attachment columns" do
it "remove the attachment columns" do
ActiveSupport::Deprecation.silence do
Dummy.connection.drop_attached_file :dummies, :avatar
end
......@@ -136,13 +136,13 @@ class SchemaTest < Test::Unit::TestCase
columns = Dummy.columns.map{ |column| [column.name, column.type] }
assert_not_includes columns, ['avatar_file_name', :string]
assert_not_includes columns, ['avatar_content_type', :string]
assert_not_includes columns, ['avatar_file_size', :integer]
assert_not_includes columns, ['avatar_updated_at', :datetime]
expect(columns).to_not include(['avatar_file_name', :string])
expect(columns).to_not include(['avatar_content_type', :string])
expect(columns).to_not include(['avatar_file_size', :integer])
expect(columns).to_not include(['avatar_updated_at', :datetime])
end
should "display a deprecation warning" do
it "display a deprecation warning" do
assert_deprecated do
Dummy.connection.drop_attached_file :dummies, :avatar
end
......@@ -151,23 +151,23 @@ class SchemaTest < Test::Unit::TestCase
context "using #remove_attachment" do
context "with single attachment" do
setup do
before do
Dummy.connection.remove_attachment :dummies, :avatar
rebuild_class
end
should "remove the attachment columns" do
it "remove the attachment columns" do
columns = Dummy.columns.map{ |column| [column.name, column.type] }
assert_not_includes columns, ['avatar_file_name', :string]
assert_not_includes columns, ['avatar_content_type', :string]
assert_not_includes columns, ['avatar_file_size', :integer]
assert_not_includes columns, ['avatar_updated_at', :datetime]
expect(columns).to_not include(['avatar_file_name', :string])
expect(columns).to_not include(['avatar_content_type', :string])
expect(columns).to_not include(['avatar_file_size', :integer])
expect(columns).to_not include(['avatar_updated_at', :datetime])
end
end
context "with multiple attachments" do
setup do
before do
Dummy.connection.change_table :dummies do |t|
t.column :photo_file_name, :string
t.column :photo_content_type, :string
......@@ -179,23 +179,23 @@ class SchemaTest < Test::Unit::TestCase
rebuild_class
end
should "remove the attachment columns" do
it "remove the attachment columns" do
columns = Dummy.columns.map{ |column| [column.name, column.type] }
assert_not_includes columns, ['avatar_file_name', :string]
assert_not_includes columns, ['avatar_content_type', :string]
assert_not_includes columns, ['avatar_file_size', :integer]
assert_not_includes columns, ['avatar_updated_at', :datetime]
assert_not_includes columns, ['photo_file_name', :string]
assert_not_includes columns, ['photo_content_type', :string]
assert_not_includes columns, ['photo_file_size', :integer]
assert_not_includes columns, ['photo_updated_at', :datetime]
expect(columns).to_not include(['avatar_file_name', :string])
expect(columns).to_not include(['avatar_content_type', :string])
expect(columns).to_not include(['avatar_file_size', :integer])
expect(columns).to_not include(['avatar_updated_at', :datetime])
expect(columns).to_not include(['photo_file_name', :string])
expect(columns).to_not include(['photo_content_type', :string])
expect(columns).to_not include(['photo_file_size', :integer])
expect(columns).to_not include(['photo_updated_at', :datetime])
end
end
context "with no attachment" do
should "raise an error" do
assert_raise ArgumentError do
it "raise an error" do
assert_raises ArgumentError do
Dummy.connection.remove_attachment :dummies
end
end
......
require './test/helper'
require 'spec_helper'
class FileSystemTest < Test::Unit::TestCase
describe Paperclip::Storage::Filesystem do
context "Filesystem" do
context "normal file" do
setup do
before do
rebuild_model :styles => { :thumbnail => "25x25#" }
@dummy = Dummy.create!
......@@ -11,23 +11,23 @@ class FileSystemTest < Test::Unit::TestCase
@dummy.avatar = @file
end
teardown { @file.close }
after { @file.close }
should "allow file assignment" do
it "allow file assignment" do
assert @dummy.save
end
should "store the original" do
it "store the original" do
@dummy.save
assert_file_exists(@dummy.avatar.path)
end
should "store the thumbnail" do
it "store the thumbnail" do
@dummy.save
assert_file_exists(@dummy.avatar.path(:thumbnail))
end
should "be rewinded after flush_writes" do
it "be rewinded after flush_writes" do
@dummy.avatar.instance_eval "def after_flush_writes; end"
files = @dummy.avatar.queued_for_write.values
......@@ -35,14 +35,14 @@ class FileSystemTest < Test::Unit::TestCase
assert files.none?(&:eof?), "Expect all the files to be rewinded."
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)
@dummy.save
assert paths.none?{ |path| File.exists?(path) },
"Expect all the files to be deleted."
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")
@dummy.avatar.copy_to_local_file(:original, tempfile.path)
tempfile.rewind
......@@ -52,7 +52,7 @@ class FileSystemTest < Test::Unit::TestCase
end
context "with file that has space in file name" do
setup do
before do
rebuild_model :styles => { :thumbnail => "25x25#" }
@dummy = Dummy.create!
......@@ -61,17 +61,17 @@ class FileSystemTest < Test::Unit::TestCase
@dummy.save
end
teardown { @file.close }
after { @file.close }
should "store the file" do
it "store the file" do
assert_file_exists(@dummy.avatar.path)
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
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
end
end
......
require './test/helper'
require 'spec_helper'
require 'fog'
class FogTest < Test::Unit::TestCase
describe Paperclip::Storage::Fog do
context "" do
setup { Fog.mock! }
before { Fog.mock! }
context "with credentials provided in a path string" do
setup do
before do
rebuild_model :styles => { :medium => "300x300>", :thumb => "100x100>" },
:storage => :fog,
:url => '/:attachment/:filename',
......@@ -17,15 +17,15 @@ class FogTest < Test::Unit::TestCase
@dummy.avatar = @file
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'
end
end
context "with credentials provided in a File object" do
setup do
before do
rebuild_model :styles => { :medium => "300x300>", :thumb => "100x100>" },
:storage => :fog,
:url => '/:attachment/:filename',
......@@ -36,15 +36,15 @@ class FogTest < Test::Unit::TestCase
@dummy.avatar = @file
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'
end
end
context "with default values for path and url" do
setup do
before do
rebuild_model :styles => { :medium => "300x300>", :thumb => "100x100>" },
:storage => :fog,
:url => '/:attachment/:filename',
......@@ -59,16 +59,16 @@ class FogTest < Test::Unit::TestCase
@dummy.avatar = @file
end
teardown { @file.close }
after { @file.close }
should "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")),
@dummy.avatar.path
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")),
@dummy.avatar.path
end
end
context "with no path or url given and using defaults" do
setup do
before do
rebuild_model :styles => { :medium => "300x300>", :thumb => "100x100>" },
:storage => :fog,
:fog_directory => "paperclip",
......@@ -83,15 +83,15 @@ class FogTest < Test::Unit::TestCase
@dummy.avatar = @file
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
end
end
context "with file params provided as lambda" do
setup do
before do
fog_file = lambda{ |a| { :custom_header => a.instance.custom_method }}
klass = rebuild_model :storage => :fog,
:fog_file => fog_file
......@@ -106,12 +106,12 @@ class FogTest < Test::Unit::TestCase
@dummy = Dummy.new
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' }
end
end
setup do
before do
@fog_directory = 'papercliptests'
@credentials = {
......@@ -137,25 +137,25 @@ class FogTest < Test::Unit::TestCase
rebuild_model(@options)
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)
end
context "when assigned" do
setup do
before do
@file = File.new(fixture_file('5k.png'), 'rb')
@dummy = Dummy.new
@dummy.avatar = @file
end
teardown do
after do
@file.close
directory = @connection.directories.new(:key => @fog_directory)
directory.files.each {|file| file.destroy}
directory.destroy
end
should "be rewinded after flush_writes" do
it "be rewinded after flush_writes" do
@dummy.avatar.instance_eval "def after_flush_writes; end"
files = @dummy.avatar.queued_for_write.values
......@@ -163,14 +163,14 @@ class FogTest < Test::Unit::TestCase
assert files.none?(&:eof?), "Expect all the files to be rewinded."
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)
@dummy.save
assert paths.none?{ |path| File.exists?(path) },
"Expect all the files to be deleted."
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
tempfile = Tempfile.new("known_location")
tempfile.binmode
......@@ -181,7 +181,7 @@ class FogTest < Test::Unit::TestCase
tempfile.close
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|
hash[:content_type]
end
......@@ -189,50 +189,50 @@ class FogTest < Test::Unit::TestCase
end
context "without a bucket" do
setup do
before do
@connection.directories.get(@fog_directory).destroy
end
should "create the bucket" do
it "create the bucket" do
assert @dummy.save
assert @connection.directories.get(@fog_directory)
end
end
context "with a bucket" do
should "succeed" do
it "succeed" do
assert @dummy.save
end
end
context "without a fog_host" do
setup do
before do
rebuild_model(@options.merge(:fog_host => nil))
@dummy = Dummy.new
@dummy.avatar = StringIO.new('.')
@dummy.save
end
should "provide a public url" do
it "provide a public url" do
assert !@dummy.avatar.url.nil?
end
end
context "with a fog_host" do
setup do
before do
rebuild_model(@options.merge(:fog_host => 'http://example.com'))
@dummy = Dummy.new
@dummy.avatar = StringIO.new(".\n")
@dummy.save
end
should "provide a public url" do
it "provide a public url" do
assert @dummy.avatar.url =~ /^http:\/\/example\.com\/avatars\/data\.txt\?\d*$/
end
end
context "with a fog_host that includes a wildcard placeholder" do
setup do
before do
rebuild_model(
:fog_directory => @fog_directory,
:fog_credentials => @credentials,
......@@ -245,27 +245,27 @@ class FogTest < Test::Unit::TestCase
@dummy.save
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*$/
end
end
context "with fog_public set to false" do
setup do
before do
rebuild_model(@options.merge(:fog_public => false))
@dummy = Dummy.new
@dummy.avatar = StringIO.new('.')
@dummy.save
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.fog_public
end
end
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>" }))
@file = File.new(fixture_file('5k.png'), 'rb')
@dummy = Dummy.new
......@@ -273,14 +273,14 @@ class FogTest < Test::Unit::TestCase
@dummy.save
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.fog_public(:thumb)
end
end
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>" }))
@file = File.new(fixture_file('5k.png'), 'rb')
@dummy = Dummy.new
......@@ -288,37 +288,37 @@ class FogTest < Test::Unit::TestCase
@dummy.save
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 true, @dummy.avatar.fog_public(:thumb)
end
end
context "with fog_public not set" do
setup do
before do
rebuild_model(@options)
@dummy = Dummy.new
@dummy.avatar = StringIO.new('.')
@dummy.save
end
should "default fog_public to true" do
it "default fog_public to true" do
assert_equal true, @dummy.avatar.fog_public
end
end
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)
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)
end
end
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)
dummy = Dummy.new
dummy.avatar = StringIO.new('.')
......@@ -326,44 +326,44 @@ class FogTest < Test::Unit::TestCase
assert_equal dummy.avatar.expiring_url(1234), dummy.avatar.expiring_url(Time.now + 1234)
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
assert_equal dummy.avatar.url, dummy.avatar.expiring_url
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
assert_equal dummy.avatar.url(:thumb), dummy.avatar.expiring_url(3600, :thumb)
end
end
context "with an invalid bucket name for a subdomain" do
setup do
before do
rebuild_model(@options.merge(:fog_directory => "this_is_invalid"))
@dummy = Dummy.new
@dummy.avatar = @file
@dummy.save
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.each do |name|
assert_no_match Paperclip::Storage::Fog::AWS_BUCKET_SUBDOMAIN_RESTRICTON_REGEX, name
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)
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)
end
end
context "with a proc for a bucket name evaluating a model method" do
setup do
before do
@dynamic_fog_directory = 'dynamicpaperclip'
rebuild_model(@options.merge(:fog_directory => lambda { |attachment| attachment.instance.bucket_name }))
@dummy = Dummy.new
......@@ -372,14 +372,14 @@ class FogTest < Test::Unit::TestCase
@dummy.save
end
should "have created the bucket" do
it "have created the bucket" do
assert @connection.directories.get(@dynamic_fog_directory).inspect
end
end
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 }))
@dummy = Dummy.new
@dummy.stubs(:fog_host).returns('http://dynamicfoghost.com')
......@@ -387,37 +387,37 @@ class FogTest < Test::Unit::TestCase
@dummy.save
end
should "provide a public url" do
it "provide a public url" do
assert_match(/http:\/\/dynamicfoghost\.com/, @dummy.avatar.url)
end
end
context "with a custom fog_host" do
setup do
before do
rebuild_model(@options.merge(:fog_host => "http://dynamicfoghost.com"))
@dummy = Dummy.new
@dummy.avatar = @file
@dummy.save
end
should "provide a public url" do
it "provide a public url" do
assert_match(/http:\/\/dynamicfoghost\.com/, @dummy.avatar.url)
end
should "provide an expiring url" do
it "provide an expiring url" do
assert_match(/http:\/\/dynamicfoghost\.com/, @dummy.avatar.expiring_url)
end
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"}))
@dummy = Dummy.new
@dummy.avatar = @file
@dummy.save
end
should "provide an expiring url" do
it "provide an expiring url" do
assert_match(/http:\/\/dynamicfoghost\.com/, @dummy.avatar.expiring_url)
end
end
......@@ -425,7 +425,7 @@ class FogTest < Test::Unit::TestCase
end
context "with a proc for the fog_credentials evaluating a model method" do
setup do
before do
@dynamic_fog_credentials = {
:provider => 'AWS',
:aws_access_key_id => 'DYNAMIC_ID',
......@@ -438,7 +438,7 @@ class FogTest < Test::Unit::TestCase
@dummy.save
end
should "provide a public url" do
it "provide a public url" do
assert_equal @dummy.avatar.fog_credentials, @dynamic_fog_credentials
end
end
......@@ -447,7 +447,7 @@ class FogTest < Test::Unit::TestCase
end
context "when using local storage" do
setup do
before do
Fog.unmock!
rebuild_model :styles => { :medium => "300x300>", :thumb => "100x100>" },
:storage => :fog,
......@@ -461,12 +461,12 @@ class FogTest < Test::Unit::TestCase
@dummy.avatar = @file
end
teardown do
after do
@file.close
Fog.mock!
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
end
end
......
require './test/helper'
require 'aws'
require 'spec_helper'
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
setup do
@s3_credentials = File.new(fixture_file("s3.yml"))
before do
rebuild_model :styles => { :thumb => "100x100", :square => "32x32#" },
:storage => :s3,
:bucket => ENV["S3_BUCKET"],
: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"))
end
should "not raise any error" do
it "not raise any error" do
@attachment = Dummy.new.avatar
@attachment.assign(@file)
@attachment.save
......@@ -25,7 +26,7 @@ unless ENV["S3_BUCKET"].blank?
@attachment2.save
end
should "allow assignment from another S3 object" do
it "allow assignment from another S3 object" do
@attachment = Dummy.new.avatar
@attachment.assign(@file)
@attachment.save
......@@ -35,62 +36,64 @@ unless ENV["S3_BUCKET"].blank?
@attachment2.save
end
teardown { [@s3_credentials, @file].each(&:close) }
after { @file.close }
end
context "Generating an expiring url on a nonexistant attachment" do
setup do
@s3_credentials = File.new(fixture_file("s3.yml"))
before do
rebuild_model :styles => { :thumb => "100x100", :square => "32x32#" },
:storage => :s3,
:bucket => ENV["S3_BUCKET"],
: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
end
should "return nil" do
assert_nil @dummy.avatar.expiring_url
it "returns a missing url" do
expect(@dummy.avatar.expiring_url).to eq @dummy.avatar.url
end
end
context "Using S3 for real, an attachment with S3 storage" do
setup do
@s3_credentials = File.new(fixture_file("s3.yml"))
before do
rebuild_model :styles => { :thumb => "100x100", :square => "32x32#" },
:storage => :s3,
:bucket => ENV["S3_BUCKET"],
: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 = Dummy.new
end
teardown { @s3_credentials.close }
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)
end
context "when assigned" do
setup do
before do
@file = File.new(fixture_file('5k.png'), 'rb')
@dummy.avatar = @file
end
teardown do
after do
@file.close
@dummy.destroy
end
context "and saved" do
setup do
before do
@dummy.save
end
should "be on S3" do
it "be on S3" do
assert true
end
end
......@@ -98,12 +101,14 @@ unless ENV["S3_BUCKET"].blank?
end
context "An attachment that uses S3 for storage and has spaces in file name" do
setup do
@s3_credentials = File.new(fixture_file("s3.yml"))
before do
rebuild_model :styles => { :thumb => "100x100", :square => "32x32#" },
:storage => :s3,
: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
@file = File.new(fixture_file('spaced file.png'), 'rb')
......@@ -112,25 +117,23 @@ unless ENV["S3_BUCKET"].blank?
@dummy.save
end
teardown { @s3_credentials.close }
should "return a replaced version for path" do
it "return a replaced version for path" do
assert_match /.+\/spaced_file\.png/, @dummy.avatar.path
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
end
should "be accessible" do
it "be accessible" do
assert_success_response @dummy.avatar.url
end
should "be reprocessable" do
it "be reprocessable" do
assert @dummy.avatar.reprocess!
end
should "be destroyable" do
it "be destroyable" do
url = @dummy.avatar.url
@dummy.destroy
assert_not_found_response url
......@@ -138,38 +141,38 @@ unless ENV["S3_BUCKET"].blank?
end
context "An attachment that uses S3 for storage and uses AES256 encryption" do
setup do
@s3_credentials = File.new(fixture_file("s3.yml"))
before do
rebuild_model :styles => { :thumb => "100x100", :square => "32x32#" },
:storage => :s3,
:bucket => ENV["S3_BUCKET"],
: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
Dummy.delete_all
@dummy = Dummy.new
end
teardown { @s3_credentials.close }
context "when assigned" do
setup do
before do
@file = File.new(fixture_file('5k.png'), 'rb')
@dummy.avatar = @file
end
teardown do
after do
@file.close
@dummy.destroy
end
context "and saved" do
setup do
before do
@dummy.save
end
should "be encrypted on S3" do
it "be encrypted on S3" do
assert @dummy.avatar.s3_object.server_side_encryption == :aes256
end
end
......
require './test/helper'
require 'aws'
require 'spec_helper'
require 'aws-sdk'
class S3Test < Test::Unit::TestCase
def rails_env(env)
silence_warnings do
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)
describe Paperclip::Storage::S3 do
before do
AWS.stub!
end
context "Parsing S3 credentials" do
setup do
before do
@proxy_settings = {:host => "127.0.0.1", :port => 8888, :user => "foo", :password => "bar"}
rebuild_model :storage => :s3,
:bucket => "testing",
:http_proxy => @proxy_settings,
:s3_credentials => {:not => :important}
:bucket => "testing",
:http_proxy => @proxy_settings,
:s3_credentials => {:not => :important}
@dummy = Dummy.new
@avatar = @dummy.avatar
end
should "get the correct credentials when RAILS_ENV is production" do
rails_env("production")
assert_equal({:key => "12345"},
@avatar.parse_credentials('production' => {:key => '12345'},
:development => {:key => "54321"}))
it "get the correct credentials when RAILS_ENV is production" do
rails_env("production") do
assert_equal({:key => "12345"},
@avatar.parse_credentials('production' => {:key => '12345'},
:development => {:key => "54321"}))
end
end
should "get the correct credentials when RAILS_ENV is development" do
rails_env("development")
assert_equal({:key => "54321"},
@avatar.parse_credentials('production' => {:key => '12345'},
:development => {:key => "54321"}))
it "get the correct credentials when RAILS_ENV is development" do
rails_env("development") do
assert_equal({:key => "54321"},
@avatar.parse_credentials('production' => {:key => '12345'},
:development => {:key => "54321"}))
end
end
should "return the argument if the key does not exist" do
rails_env("not really an env")
assert_equal({:test => "12345"}, @avatar.parse_credentials(:test => "12345"))
it "return the argument if the key does not exist" do
rails_env("not really an env") do
assert_equal({:test => "12345"}, @avatar.parse_credentials(:test => "12345"))
end
end
should "support HTTP proxy settings" do
rails_env("development")
assert_equal(true, @avatar.using_http_proxy?)
assert_equal(@proxy_settings[:host], @avatar.http_proxy_host)
assert_equal(@proxy_settings[:port], @avatar.http_proxy_port)
assert_equal(@proxy_settings[:user], @avatar.http_proxy_user)
assert_equal(@proxy_settings[:password], @avatar.http_proxy_password)
it "support HTTP proxy settings" do
rails_env("development") do
assert_equal(true, @avatar.using_http_proxy?)
assert_equal(@proxy_settings[:host], @avatar.http_proxy_host)
assert_equal(@proxy_settings[:port], @avatar.http_proxy_port)
assert_equal(@proxy_settings[:user], @avatar.http_proxy_user)
assert_equal(@proxy_settings[:password], @avatar.http_proxy_password)
end
end
end
context ":bucket option via :s3_credentials" do
setup do
before do
rebuild_model :storage => :s3, :s3_credentials => {:bucket => 'testing'}
@dummy = Dummy.new
end
should "populate #bucket_name" do
it "populate #bucket_name" do
assert_equal @dummy.avatar.bucket_name, 'testing'
end
......@@ -73,12 +67,12 @@ class S3Test < Test::Unit::TestCase
context ":bucket option" do
setup do
before do
rebuild_model :storage => :s3, :bucket => "testing", :s3_credentials => {}
@dummy = Dummy.new
end
should "populate #bucket_name" do
it "populate #bucket_name" do
assert_equal @dummy.avatar.bucket_name, 'testing'
end
......@@ -86,43 +80,42 @@ class S3Test < Test::Unit::TestCase
context "missing :bucket option" do
setup do
before do
rebuild_model :storage => :s3,
:http_proxy => @proxy_settings,
:s3_credentials => {:not => :important}
:http_proxy => @proxy_settings,
:s3_credentials => {:not => :important}
@dummy = Dummy.new
@dummy.avatar = stringy_file
end
should "raise an argument error" do
exception = assert_raise(ArgumentError) { @dummy.save }
assert_match /missing required :bucket option/, exception.message
it "raise an argument error" do
expect { @dummy.save }.to raise_error(ArgumentError, /missing required :bucket option/)
end
end
context "" do
setup do
before do
rebuild_model :storage => :s3,
:s3_credentials => {},
:bucket => "bucket",
:path => ":attachment/:basename.:extension",
:url => ":s3_path_url"
:s3_credentials => {},
:bucket => "bucket",
:path => ":attachment/:basename.:extension",
:url => ":s3_path_url"
@dummy = Dummy.new
@dummy.avatar = stringy_file
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
end
should "use the correct bucket" do
it "use the correct bucket" do
assert_equal "bucket", @dummy.avatar.s3_bucket.name
end
should "use the correct key" do
it "use the correct key" do
assert_equal "avatars/data.txt", @dummy.avatar.s3_object.key
end
end
......@@ -130,13 +123,13 @@ class S3Test < Test::Unit::TestCase
context "s3_protocol" do
["http", :http, ""].each do |protocol|
context "as #{protocol.inspect}" do
setup do
before do
rebuild_model :storage => :s3, :s3_protocol => protocol
@dummy = Dummy.new
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
end
end
......@@ -144,107 +137,107 @@ class S3Test < Test::Unit::TestCase
end
context ":s3_protocol => 'https'" do
setup do
before do
rebuild_model :storage => :s3,
:s3_credentials => {},
:s3_protocol => 'https',
:bucket => "bucket",
:path => ":attachment/:basename.:extension"
:s3_credentials => {},
:s3_protocol => 'https',
:bucket => "bucket",
:path => ":attachment/:basename.:extension"
@dummy = Dummy.new
@dummy.avatar = stringy_file
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
end
end
context ":s3_protocol => :https" do
setup do
before do
rebuild_model :storage => :s3,
:s3_credentials => {},
:s3_protocol => :https,
:bucket => "bucket",
:path => ":attachment/:basename.:extension"
:s3_credentials => {},
:s3_protocol => :https,
:bucket => "bucket",
:path => ":attachment/:basename.:extension"
@dummy = Dummy.new
@dummy.avatar = stringy_file
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
end
end
context ":s3_protocol => ''" do
setup do
before do
rebuild_model :storage => :s3,
:s3_credentials => {},
:s3_protocol => '',
:bucket => "bucket",
:path => ":attachment/:basename.:extension"
:s3_credentials => {},
:s3_protocol => '',
:bucket => "bucket",
:path => ":attachment/:basename.:extension"
@dummy = Dummy.new
@dummy.avatar = stringy_file
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
end
end
context "An attachment that uses S3 for storage and has the style in the path" do
setup do
before do
rebuild_model :storage => :s3,
:bucket => "testing",
:path => ":attachment/:style/:basename.:extension",
:styles => {
:thumb => "80x80>"
},
:s3_credentials => {
'access_key_id' => "12345",
'secret_access_key' => "54321"
}
:bucket => "testing",
:path => ":attachment/:style/:basename.:extension",
:styles => {
:thumb => "80x80>"
},
:s3_credentials => {
'access_key_id' => "12345",
'secret_access_key' => "54321"
}
@dummy = Dummy.new
@dummy.avatar = stringy_file
@avatar = @dummy.avatar
@dummy = Dummy.new
@dummy.avatar = stringy_file
@avatar = @dummy.avatar
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)
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)
end
end
context "s3_host_name" do
setup do
before do
rebuild_model :storage => :s3,
:s3_credentials => {},
:bucket => "bucket",
:path => ":attachment/:basename.:extension",
:s3_host_name => "s3-ap-northeast-1.amazonaws.com"
:s3_credentials => {},
:bucket => "bucket",
:path => ":attachment/:basename.:extension",
:s3_host_name => "s3-ap-northeast-1.amazonaws.com"
@dummy = Dummy.new
@dummy.avatar = stringy_file
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
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
end
end
context "dynamic s3_host_name" do
setup do
before do
rebuild_model :storage => :s3,
:s3_credentials => {},
:bucket => "bucket",
:path => ":attachment/:basename.:extension",
:s3_host_name => lambda {|a| a.instance.value }
:s3_credentials => {},
:bucket => "bucket",
:path => ":attachment/:basename.:extension",
:s3_host_name => lambda {|a| a.instance.value }
@dummy = Dummy.new
class << @dummy
attr_accessor :value
......@@ -252,183 +245,183 @@ class S3Test < Test::Unit::TestCase
@dummy.avatar = stringy_file
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"
assert_equal "http://s3.something.com/bucket/avatars/data.txt", @dummy.avatar.url(:original, :timestamp => false)
end
end
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] },
:storage => :s3,
:bucket => "bucket",
:path => ":attachment/:basename.:extension",
:s3_credentials => {
'access_key_id' => "12345",
'secret_access_key' => "54321"
}
File.open(fixture_file('5k.png'), 'rb') do |file|
@dummy = Dummy.new
@dummy.avatar = file
end
:storage => :s3,
:bucket => "bucket",
:path => ":attachment/:basename.:extension",
:s3_credentials => {
'access_key_id' => "12345",
'secret_access_key' => "54321"
}
File.open(fixture_file('5k.png'), 'rb') do |file|
@dummy = Dummy.new
@dummy.avatar = file
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
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
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)
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
end
end
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'}} }},
:storage => :s3,
:bucket => "bucket",
:path => ":attachment/:style/:basename.:extension",
:s3_credentials => {
'access_key_id' => "12345",
'secret_access_key' => "54321"
}
:storage => :s3,
:bucket => "bucket",
:path => ":attachment/:style/:basename.:extension",
:s3_credentials => {
'access_key_id' => "12345",
'secret_access_key' => "54321"
}
@file = File.new(fixture_file('5k.png'), 'rb')
@file = File.new(fixture_file('5k.png'), 'rb')
Dummy.class_eval do
def counter
@counter ||= 0
@counter += 1
@counter
Dummy.class_eval do
def counter
@counter ||= 0
@counter += 1
@counter
end
end
end
@dummy = Dummy.new
@dummy.avatar = @file
@dummy = Dummy.new
@dummy.avatar = @file
object = stub
@dummy.avatar.stubs(:s3_object).with(:original).returns(object)
@dummy.avatar.stubs(:s3_object).with(:thumbnail).returns(object)
object.expects(:write).with(anything, :content_type => 'image/png', :acl => :public_read)
object.expects(:write).with(anything, :content_type => 'image/png', :acl => :public_read, :cache_control => 'max-age=31557600')
@dummy.save
object = stub
@dummy.avatar.stubs(:s3_object).with(:original).returns(object)
@dummy.avatar.stubs(:s3_object).with(:thumbnail).returns(object)
object.expects(:write).with(anything, :content_type => 'image/png', :acl => :public_read)
object.expects(:write).with(anything, :content_type => 'image/png', :acl => :public_read, :cache_control => 'max-age=31557600')
@dummy.save
end
teardown { @file.close }
after { @file.close }
should "succeed" do
it "succeed" do
assert_equal @dummy.counter, 7
end
end
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] },
:storage => :s3,
:bucket => "bucket",
:s3_credentials => {
'access_key_id' => "12345",
'secret_access_key' => "54321"
}
File.open(fixture_file('spaced file.png'), 'rb') do |file|
@dummy = Dummy.new
@dummy.avatar = file
end
:storage => :s3,
:bucket => "bucket",
:s3_credentials => {
'access_key_id' => "12345",
'secret_access_key' => "54321"
}
File.open(fixture_file('spaced file.png'), 'rb') do |file|
@dummy = Dummy.new
@dummy.avatar = file
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
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
end
end
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] },
:storage => :s3,
:bucket => "bucket",
:s3_credentials => {
'access_key_id' => "12345",
'secret_access_key' => "54321"
}
stringio = stringy_file
class << stringio
def original_filename
"question?mark.png"
:storage => :s3,
:bucket => "bucket",
:s3_credentials => {
'access_key_id' => "12345",
'secret_access_key' => "54321"
}
stringio = stringy_file
class << stringio
def original_filename
"question?mark.png"
end
end
end
file = Paperclip.io_adapters.for(stringio)
@dummy = Dummy.new
@dummy.avatar = file
@dummy.save
file = Paperclip.io_adapters.for(stringio)
@dummy = Dummy.new
@dummy.avatar = file
@dummy.save
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
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
end
end
context "" do
setup do
before do
rebuild_model :storage => :s3,
:s3_credentials => {},
:bucket => "bucket",
:path => ":attachment/:basename.:extension",
:url => ":s3_domain_url"
:s3_credentials => {},
:bucket => "bucket",
:path => ":attachment/:basename.:extension",
:url => ":s3_domain_url"
@dummy = Dummy.new
@dummy.avatar = stringy_file
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
end
end
context "" do
setup do
before do
rebuild_model :storage => :s3,
:s3_credentials => {
:production => { :bucket => "prod_bucket" },
:development => { :bucket => "dev_bucket" }
},
:s3_host_alias => "something.something.com",
:path => ":attachment/:basename.:extension",
:url => ":s3_alias_url"
:s3_credentials => {
:production => { :bucket => "prod_bucket" },
:development => { :bucket => "dev_bucket" }
},
:s3_host_alias => "something.something.com",
:path => ":attachment/:basename.:extension",
:url => ":s3_alias_url"
@dummy = Dummy.new
@dummy.avatar = stringy_file
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
end
end
context "generating a url with a proc as the host alias" do
setup do
before do
rebuild_model :storage => :s3,
:s3_credentials => { :bucket => "prod_bucket" },
:s3_host_alias => Proc.new{|atch| "cdn#{atch.instance.counter % 4}.example.com"},
:path => ":attachment/:basename.:extension",
:url => ":s3_alias_url"
:s3_credentials => { :bucket => "prod_bucket" },
:s3_host_alias => Proc.new{|atch| "cdn#{atch.instance.counter % 4}.example.com"},
:path => ":attachment/:basename.:extension",
:url => ":s3_alias_url"
Dummy.class_eval do
def counter
@counter ||= 0
......@@ -440,36 +433,36 @@ class S3Test < Test::Unit::TestCase
@dummy.avatar = stringy_file
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://cdn2.example.com/avatars/data.txt}, @dummy.avatar.url
end
should "still return the bucket name" do
it "still return the bucket name" do
assert_equal "prod_bucket", @dummy.avatar.bucket_name
end
end
context "" do
setup do
before do
rebuild_model :storage => :s3,
:s3_credentials => {},
:bucket => "bucket",
:path => ":attachment/:basename.:extension",
:url => ":asset_host"
:s3_credentials => {},
:bucket => "bucket",
:path => ":attachment/:basename.:extension",
:url => ":asset_host"
@dummy = Dummy.new
@dummy.avatar = stringy_file
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
end
end
context "Generating a secure url with an expiration" do
setup do
before do
@build_model_with_options = lambda {|options|
base_options = {
:storage => :s3,
......@@ -487,105 +480,105 @@ class S3Test < Test::Unit::TestCase
}
end
should "use default options" do
it "use default options" do
@build_model_with_options[{}]
rails_env("production")
rails_env("production") do
@dummy = Dummy.new
@dummy.avatar = stringy_file
@dummy = Dummy.new
@dummy.avatar = stringy_file
object = stub
@dummy.avatar.stubs(:s3_object).returns(object)
object.expects(:url_for).with(:read, :expires => 3600, :secure => true)
object = stub
@dummy.avatar.stubs(:s3_object).returns(object)
object.expects(:url_for).with(:read, :expires => 3600, :secure => true)
@dummy.avatar.expiring_url
@dummy.avatar.expiring_url
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" }]
rails_env("production")
rails_env("production") do
@dummy = Dummy.new
@dummy.avatar = stringy_file
@dummy = Dummy.new
@dummy.avatar = stringy_file
object = stub
@dummy.avatar.stubs(:s3_object).returns(object)
object.expects(:url_for).with(:read, :expires => 3600, :secure => true, :response_content_disposition => "inline")
object = stub
@dummy.avatar.stubs(:s3_object).returns(object)
object.expects(:url_for).with(:read, :expires => 3600, :secure => true, :response_content_disposition => "inline")
@dummy.avatar.expiring_url
@dummy.avatar.expiring_url
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 } }]
rails_env("production")
@dummy = Dummy.new
rails_env("production") do
@dummy = Dummy.new
@file = stringy_file
@file.stubs(:original_filename).returns("5k.png\n\n")
Paperclip.stubs(:run).returns('image/png')
@file.stubs(:content_type).returns("image/png\n\n")
@file.stubs(:to_tempfile).returns(@file)
@file = stringy_file
@file.stubs(:original_filename).returns("5k.png\n\n")
Paperclip.stubs(:run).returns('image/png')
@file.stubs(:content_type).returns("image/png\n\n")
@file.stubs(:to_tempfile).returns(@file)
@dummy.avatar = @file
@dummy.avatar = @file
object = stub
@dummy.avatar.stubs(:s3_object).returns(object)
object.expects(:url_for).with(:read, :expires => 3600, :secure => true, :response_content_type => "image/png")
object = stub
@dummy.avatar.stubs(:s3_object).returns(object)
object.expects(:url_for).with(:read, :expires => 3600, :secure => true, :response_content_type => "image/png")
@dummy.avatar.expiring_url
@dummy.avatar.expiring_url
end
end
end
context "#expiring_url" do
setup { @dummy = Dummy.new }
before { @dummy = Dummy.new }
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)
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))
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)
end
end
context "Generating a url with an expiration for each style" do
setup do
before do
rebuild_model :storage => :s3,
:s3_credentials => {
:production => { :bucket => "prod_bucket" },
:development => { :bucket => "dev_bucket" }
},
:s3_permissions => :private,
:s3_host_alias => "something.something.com",
:path => ":attachment/:style/:basename.:extension",
:url => ":s3_alias_url"
rails_env("production")
@dummy = Dummy.new
@dummy.avatar = stringy_file
:s3_credentials => {
:production => { :bucket => "prod_bucket" },
:development => { :bucket => "dev_bucket" }
},
:s3_permissions => :private,
:s3_host_alias => "something.something.com",
:path => ":attachment/:style/:basename.:extension",
:url => ":s3_alias_url"
rails_env("production") do
@dummy = Dummy.new
@dummy.avatar = stringy_file
end
end
should "should generate a url for the thumb" do
it "should generate a url for the thumb" do
object = stub
@dummy.avatar.stubs(:s3_object).with(:thumb).returns(object)
object.expects(:url_for).with(:read, :expires => 1800, :secure => true)
@dummy.avatar.expiring_url(1800, :thumb)
end
should "should generate a url for the default style" do
it "should generate a url for the default style" do
object = stub
@dummy.avatar.stubs(:s3_object).with(:original).returns(object)
object.expects(:url_for).with(:read, :expires => 1800, :secure => true)
......@@ -594,101 +587,108 @@ class S3Test < Test::Unit::TestCase
end
context "Parsing S3 credentials with a bucket in them" do
setup do
before do
rebuild_model :storage => :s3,
:s3_credentials => {
:production => { :bucket => "prod_bucket" },
:development => { :bucket => "dev_bucket" }
}
@dummy = Dummy.new
:s3_credentials => {
:production => { :bucket => "prod_bucket" },
:development => { :bucket => "dev_bucket" }
}
@dummy = Dummy.new
end
should "get the right bucket in production" do
rails_env("production")
assert_equal "prod_bucket", @dummy.avatar.bucket_name
assert_equal "prod_bucket", @dummy.avatar.s3_bucket.name
it "get the right bucket in production" do
rails_env("production") do
assert_equal "prod_bucket", @dummy.avatar.bucket_name
assert_equal "prod_bucket", @dummy.avatar.s3_bucket.name
end
end
should "get the right bucket in development" do
rails_env("development")
assert_equal "dev_bucket", @dummy.avatar.bucket_name
assert_equal "dev_bucket", @dummy.avatar.s3_bucket.name
it "get the right bucket in development" do
rails_env("development") do
assert_equal "dev_bucket", @dummy.avatar.bucket_name
assert_equal "dev_bucket", @dummy.avatar.s3_bucket.name
end
end
end
context "Parsing S3 credentials with a s3_host_name in them" do
setup do
before do
rebuild_model :storage => :s3,
:bucket => 'testing',
:s3_credentials => {
:production => { :s3_host_name => "s3-world-end.amazonaws.com" },
:development => { :s3_host_name => "s3-ap-northeast-1.amazonaws.com" }
}
@dummy = Dummy.new
:bucket => 'testing',
:s3_credentials => {
:production => { :s3_host_name => "s3-world-end.amazonaws.com" },
:development => { :s3_host_name => "s3-ap-northeast-1.amazonaws.com" }
}
@dummy = Dummy.new
end
should "get the right s3_host_name in production" do
rails_env("production")
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
it "get the right s3_host_name in production" do
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_bucket.config.s3_endpoint
end
end
should "get the right s3_host_name in development" do
rails_env("development")
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
it "get the right s3_host_name in development" do
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_bucket.config.s3_endpoint
end
end
should "get the right s3_host_name if the key does not exist" do
rails_env("test")
assert_match %r{^s3.amazonaws.com}, @dummy.avatar.s3_host_name
assert_match %r{^s3.amazonaws.com}, @dummy.avatar.s3_bucket.config.s3_endpoint
it "get the right s3_host_name if the key does not exist" do
rails_env("test") do
assert_match %r{^s3.amazonaws.com}, @dummy.avatar.s3_host_name
assert_match %r{^s3.amazonaws.com}, @dummy.avatar.s3_bucket.config.s3_endpoint
end
end
end
context "An attachment with S3 storage" do
setup do
before do
rebuild_model :storage => :s3,
:bucket => "testing",
:path => ":attachment/:style/:basename.:extension",
:s3_credentials => {
'access_key_id' => "12345",
'secret_access_key' => "54321"
}
:bucket => "testing",
:path => ":attachment/:style/:basename.:extension",
:s3_credentials => {
:aws_access_key_id => "12345",
:aws_secret_access_key => "54321"
}
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)
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)
end
context "when assigned" do
setup do
before do
@file = File.new(fixture_file('5k.png'), 'rb')
@dummy = Dummy.new
@dummy.avatar = @file
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_bucket).never
assert_match %r{^http://s3\.amazonaws\.com/testing/avatars/original/5k\.png}, @dummy.avatar.url
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.stubs(:s3_object).returns(stub(write: true))
files = @dummy.avatar.queued_for_write.values.each(&:read)
@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
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)
@dummy.save
assert paths.none?{ |path| File.exists?(path) },
......@@ -696,7 +696,7 @@ class S3Test < Test::Unit::TestCase
end
context "and saved" do
setup do
before do
object = stub
@dummy.avatar.stubs(:s3_object).returns(object)
object.expects(:write).with(anything,
......@@ -705,45 +705,45 @@ class S3Test < Test::Unit::TestCase
@dummy.save
end
should "succeed" do
it "succeed" do
assert true
end
end
context "and saved without a bucket" do
setup do
before do
AWS::S3::BucketCollection.any_instance.expects(:create).with("testing")
AWS::S3::S3Object.any_instance.stubs(:write).
raises(AWS::S3::Errors::NoSuchBucket.new(stub,
stub(:status => 404,
:body => "<foo/>"))).
then.returns(nil)
then.returns(nil)
@dummy.save
end
should "succeed" do
it "succeed" do
assert true
end
end
context "and remove" do
setup do
before do
AWS::S3::S3Object.any_instance.stubs(:exists?).returns(true)
AWS::S3::S3Object.any_instance.stubs(:delete)
@dummy.destroy
end
should "succeed" do
it "succeed" do
assert true
end
end
context 'that the file were missing' do
setup do
before do
AWS::S3::S3Object.any_instance.stubs(:exists?).raises(AWS::Errors::Base)
end
should 'return false on exists?' do
it 'return false on exists?' do
assert !@dummy.avatar.exists?
end
end
......@@ -751,13 +751,13 @@ class S3Test < Test::Unit::TestCase
end
context "An attachment with S3 storage and bucket defined as a Proc" do
setup do
before do
rebuild_model :storage => :s3,
:bucket => lambda { |attachment| "bucket_#{attachment.instance.other}" },
:s3_credentials => {:not => :important}
:bucket => lambda { |attachment| "bucket_#{attachment.instance.other}" },
:s3_credentials => {:not => :important}
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.s3_bucket.name
assert "bucket_b", Dummy.new(:other => 'b').avatar.bucket_name
......@@ -766,84 +766,84 @@ class S3Test < Test::Unit::TestCase
end
context "An attachment with S3 storage and S3 credentials defined as a Proc" do
setup do
before do
rebuild_model :storage => :s3,
:bucket => {:not => :important},
:s3_credentials => lambda { |attachment|
Hash['access_key_id' => "access#{attachment.instance.other}", 'secret_access_key' => "secret#{attachment.instance.other}"]
}
:bucket => {:not => :important},
:s3_credentials => lambda { |attachment|
Hash['access_key_id' => "access#{attachment.instance.other}", 'secret_access_key' => "secret#{attachment.instance.other}"]
}
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 "secret1234", Dummy.new(:other => '1234').avatar.s3_credentials[:secret_access_key]
end
end
context "An attachment with S3 storage and S3 credentials with a :credential_provider" do
setup do
before do
class DummyCredentialProvider; end
rebuild_model :storage => :s3,
:bucket => "testing",
:s3_credentials => {
:credential_provider => DummyCredentialProvider.new
}
@dummy = Dummy.new
:bucket => "testing",
:s3_credentials => {
:credential_provider => DummyCredentialProvider.new
}
@dummy = Dummy.new
end
should "set the credential-provider" do
assert_kind_of DummyCredentialProvider, @dummy.avatar.s3_bucket.config.credential_provider
it "set the credential-provider" do
expect(@dummy.avatar.s3_bucket.config.credential_provider).to be_a DummyCredentialProvider
end
end
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"]
@dummy = Dummy.new
end
should "not accept the credentials" do
assert_raise(ArgumentError) do
it "not accept the credentials" do
assert_raises(ArgumentError) do
@dummy.avatar.s3_credentials
end
end
end
context "An attachment with S3 storage and S3 credentials not supplied" do
setup do
before do
rebuild_model :storage => :s3, :bucket => "testing"
@dummy = Dummy.new
end
should "not parse any credentials" do
it "not parse any credentials" do
assert_equal({}, @dummy.avatar.s3_credentials)
end
end
context "An attachment with S3 storage and specific s3 headers set" do
setup do
before do
rebuild_model :storage => :s3,
:bucket => "testing",
:path => ":attachment/:style/:basename.:extension",
:s3_credentials => {
'access_key_id' => "12345",
'secret_access_key' => "54321"
},
:s3_headers => {'Cache-Control' => 'max-age=31557600'}
:bucket => "testing",
:path => ":attachment/:style/:basename.:extension",
:s3_credentials => {
'access_key_id' => "12345",
'secret_access_key' => "54321"
},
:s3_headers => {'Cache-Control' => 'max-age=31557600'}
end
context "when assigned" do
setup do
before do
@file = File.new(fixture_file('5k.png'), 'rb')
@dummy = Dummy.new
@dummy.avatar = @file
end
teardown { @file.close }
after { @file.close }
context "and saved" do
setup do
before do
object = stub
@dummy.avatar.stubs(:s3_object).returns(object)
object.expects(:write).with(anything,
......@@ -853,7 +853,7 @@ class S3Test < Test::Unit::TestCase
@dummy.save
end
should "succeed" do
it "succeed" do
assert true
end
end
......@@ -861,28 +861,28 @@ class S3Test < Test::Unit::TestCase
end
context "An attachment with S3 storage and metadata set using header names" do
setup do
before do
rebuild_model :storage => :s3,
:bucket => "testing",
:path => ":attachment/:style/:basename.:extension",
:s3_credentials => {
'access_key_id' => "12345",
'secret_access_key' => "54321"
},
:s3_headers => {'x-amz-meta-color' => 'red'}
:bucket => "testing",
:path => ":attachment/:style/:basename.:extension",
:s3_credentials => {
'access_key_id' => "12345",
'secret_access_key' => "54321"
},
:s3_headers => {'x-amz-meta-color' => 'red'}
end
context "when assigned" do
setup do
before do
@file = File.new(fixture_file('5k.png'), 'rb')
@dummy = Dummy.new
@dummy.avatar = @file
end
teardown { @file.close }
after { @file.close }
context "and saved" do
setup do
before do
object = stub
@dummy.avatar.stubs(:s3_object).returns(object)
object.expects(:write).with(anything,
......@@ -892,7 +892,7 @@ class S3Test < Test::Unit::TestCase
@dummy.save
end
should "succeed" do
it "succeed" do
assert true
end
end
......@@ -900,28 +900,28 @@ class S3Test < Test::Unit::TestCase
end
context "An attachment with S3 storage and metadata set using the :s3_metadata option" do
setup do
before do
rebuild_model :storage => :s3,
:bucket => "testing",
:path => ":attachment/:style/:basename.:extension",
:s3_credentials => {
'access_key_id' => "12345",
'secret_access_key' => "54321"
},
:s3_metadata => { "color" => "red" }
:bucket => "testing",
:path => ":attachment/:style/:basename.:extension",
:s3_credentials => {
'access_key_id' => "12345",
'secret_access_key' => "54321"
},
:s3_metadata => { "color" => "red" }
end
context "when assigned" do
setup do
before do
@file = File.new(fixture_file('5k.png'), 'rb')
@dummy = Dummy.new
@dummy.avatar = @file
end
teardown { @file.close }
after { @file.close }
context "and saved" do
setup do
before do
object = stub
@dummy.avatar.stubs(:s3_object).returns(object)
object.expects(:write).with(anything,
......@@ -931,7 +931,7 @@ class S3Test < Test::Unit::TestCase
@dummy.save
end
should "succeed" do
it "succeed" do
assert true
end
end
......@@ -939,28 +939,28 @@ class S3Test < Test::Unit::TestCase
end
context "An attachment with S3 storage and storage class set using the header name" do
setup do
before do
rebuild_model :storage => :s3,
:bucket => "testing",
:path => ":attachment/:style/:basename.:extension",
:s3_credentials => {
'access_key_id' => "12345",
'secret_access_key' => "54321"
},
:s3_headers => { "x-amz-storage-class" => "reduced_redundancy" }
:bucket => "testing",
:path => ":attachment/:style/:basename.:extension",
:s3_credentials => {
'access_key_id' => "12345",
'secret_access_key' => "54321"
},
:s3_headers => { "x-amz-storage-class" => "reduced_redundancy" }
end
context "when assigned" do
setup do
before do
@file = File.new(fixture_file('5k.png'), 'rb')
@dummy = Dummy.new
@dummy.avatar = @file
end
teardown { @file.close }
after { @file.close }
context "and saved" do
setup do
before do
object = stub
@dummy.avatar.stubs(:s3_object).returns(object)
object.expects(:write).with(anything,
......@@ -970,7 +970,7 @@ class S3Test < Test::Unit::TestCase
@dummy.save
end
should "succeed" do
it "succeed" do
assert true
end
end
......@@ -979,7 +979,7 @@ class S3Test < Test::Unit::TestCase
context "Can disable AES256 encryption multiple ways" do
[nil, false, ''].each do |tech|
setup do
before do
rebuild_model(
:storage => :s3,
:bucket => "testing",
......@@ -987,29 +987,29 @@ class S3Test < Test::Unit::TestCase
:s3_credentials => {
'access_key_id' => "12345",
'secret_access_key' => "54321"},
:s3_server_side_encryption => tech)
:s3_server_side_encryption => tech)
end
context "when assigned" do
setup do
before do
@file = File.new(fixture_file('5k.png'), 'rb')
@dummy = Dummy.new
@dummy.avatar = @file
end
teardown { @file.close }
after { @file.close }
context "and saved" do
setup do
before do
object = stub
@dummy.avatar.stubs(:s3_object).returns(object)
object.expects(:write).with(anything,
:content_type => "image/png",
:acl => :public_read)
:content_type => "image/png",
:acl => :public_read)
@dummy.save
end
should "succeed" do
it "succeed" do
assert true
end
end
......@@ -1018,28 +1018,28 @@ class S3Test < Test::Unit::TestCase
end
context "An attachment with S3 storage and using AES256 encryption" do
setup do
before do
rebuild_model :storage => :s3,
:bucket => "testing",
:path => ":attachment/:style/:basename.:extension",
:s3_credentials => {
'access_key_id' => "12345",
'secret_access_key' => "54321"
},
:s3_server_side_encryption => :aes256
:bucket => "testing",
:path => ":attachment/:style/:basename.:extension",
:s3_credentials => {
'access_key_id' => "12345",
'secret_access_key' => "54321"
},
:s3_server_side_encryption => :aes256
end
context "when assigned" do
setup do
before do
@file = File.new(fixture_file('5k.png'), 'rb')
@dummy = Dummy.new
@dummy.avatar = @file
end
teardown { @file.close }
after { @file.close }
context "and saved" do
setup do
before do
object = stub
@dummy.avatar.stubs(:s3_object).returns(object)
object.expects(:write).with(anything,
......@@ -1049,7 +1049,7 @@ class S3Test < Test::Unit::TestCase
@dummy.save
end
should "succeed" do
it "succeed" do
assert true
end
end
......@@ -1057,28 +1057,28 @@ class S3Test < Test::Unit::TestCase
end
context "An attachment with S3 storage and storage class set using the :storage_class option" do
setup do
before do
rebuild_model :storage => :s3,
:bucket => "testing",
:path => ":attachment/:style/:basename.:extension",
:s3_credentials => {
'access_key_id' => "12345",
'secret_access_key' => "54321"
},
:s3_storage_class => :reduced_redundancy
:bucket => "testing",
:path => ":attachment/:style/:basename.:extension",
:s3_credentials => {
'access_key_id' => "12345",
'secret_access_key' => "54321"
},
:s3_storage_class => :reduced_redundancy
end
context "when assigned" do
setup do
before do
@file = File.new(fixture_file('5k.png'), 'rb')
@dummy = Dummy.new
@dummy.avatar = @file
end
teardown { @file.close }
after { @file.close }
context "and saved" do
setup do
before do
object = stub
@dummy.avatar.stubs(:s3_object).returns(object)
object.expects(:write).with(anything,
......@@ -1088,7 +1088,7 @@ class S3Test < Test::Unit::TestCase
@dummy.save
end
should "succeed" do
it "succeed" do
assert true
end
end
......@@ -1096,21 +1096,21 @@ class S3Test < Test::Unit::TestCase
end
context "with S3 credentials supplied as Pathname" do
setup do
before do
ENV['S3_KEY'] = 'pathname_key'
ENV['S3_BUCKET'] = 'pathname_bucket'
ENV['S3_SECRET'] = 'pathname_secret'
rails_env('test')
rebuild_model :storage => :s3,
:s3_credentials => Pathname.new(fixture_file('s3.yml'))
rails_env('test') do
rebuild_model :storage => :s3,
:s3_credentials => Pathname.new(fixture_file('s3.yml'))
Dummy.delete_all
@dummy = Dummy.new
Dummy.delete_all
@dummy = Dummy.new
end
end
should "parse the credentials" do
it "parse the credentials" do
assert_equal 'pathname_bucket', @dummy.avatar.bucket_name
assert_equal 'pathname_key', @dummy.avatar.s3_bucket.config.access_key_id
assert_equal 'pathname_secret', @dummy.avatar.s3_bucket.config.secret_access_key
......@@ -1118,22 +1118,22 @@ class S3Test < Test::Unit::TestCase
end
context "with S3 credentials in a YAML file" do
setup do
before do
ENV['S3_KEY'] = 'env_key'
ENV['S3_BUCKET'] = 'env_bucket'
ENV['S3_SECRET'] = 'env_secret'
rails_env('test')
rails_env('test') do
rebuild_model :storage => :s3,
:s3_credentials => File.new(fixture_file('s3.yml'))
rebuild_model :storage => :s3,
:s3_credentials => File.new(fixture_file('s3.yml'))
Dummy.delete_all
Dummy.delete_all
@dummy = Dummy.new
@dummy = Dummy.new
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_key', @dummy.avatar.s3_bucket.config.access_key_id
assert_equal 'env_secret', @dummy.avatar.s3_bucket.config.secret_access_key
......@@ -1142,27 +1142,27 @@ class S3Test < Test::Unit::TestCase
context "S3 Permissions" do
context "defaults to :public_read" do
setup do
before do
rebuild_model :storage => :s3,
:bucket => "testing",
:path => ":attachment/:style/:basename.:extension",
:s3_credentials => {
'access_key_id' => "12345",
'secret_access_key' => "54321"
}
:bucket => "testing",
:path => ":attachment/:style/:basename.:extension",
:s3_credentials => {
'access_key_id' => "12345",
'secret_access_key' => "54321"
}
end
context "when assigned" do
setup do
before do
@file = File.new(fixture_file('5k.png'), 'rb')
@dummy = Dummy.new
@dummy.avatar = @file
end
teardown { @file.close }
after { @file.close }
context "and saved" do
setup do
before do
object = stub
@dummy.avatar.stubs(:s3_object).returns(object)
object.expects(:write).with(anything,
......@@ -1171,7 +1171,7 @@ class S3Test < Test::Unit::TestCase
@dummy.save
end
should "succeed" do
it "succeed" do
assert true
end
end
......@@ -1179,28 +1179,28 @@ class S3Test < Test::Unit::TestCase
end
context "string permissions set" do
setup do
before do
rebuild_model :storage => :s3,
:bucket => "testing",
:path => ":attachment/:style/:basename.:extension",
:s3_credentials => {
'access_key_id' => "12345",
'secret_access_key' => "54321"
},
:s3_permissions => :private
:bucket => "testing",
:path => ":attachment/:style/:basename.:extension",
:s3_credentials => {
'access_key_id' => "12345",
'secret_access_key' => "54321"
},
:s3_permissions => :private
end
context "when assigned" do
setup do
before do
@file = File.new(fixture_file('5k.png'), 'rb')
@dummy = Dummy.new
@dummy.avatar = @file
end
teardown { @file.close }
after { @file.close }
context "and saved" do
setup do
before do
object = stub
@dummy.avatar.stubs(:s3_object).returns(object)
object.expects(:write).with(anything,
......@@ -1209,7 +1209,7 @@ class S3Test < Test::Unit::TestCase
@dummy.save
end
should "succeed" do
it "succeed" do
assert true
end
end
......@@ -1217,34 +1217,34 @@ class S3Test < Test::Unit::TestCase
end
context "hash permissions set" do
setup do
before do
rebuild_model :storage => :s3,
:bucket => "testing",
:path => ":attachment/:style/:basename.:extension",
:styles => {
:thumb => "80x80>"
},
:s3_credentials => {
'access_key_id' => "12345",
'secret_access_key' => "54321"
},
:s3_permissions => {
:original => :private,
:thumb => :public_read
}
:bucket => "testing",
:path => ":attachment/:style/:basename.:extension",
:styles => {
:thumb => "80x80>"
},
:s3_credentials => {
'access_key_id' => "12345",
'secret_access_key' => "54321"
},
:s3_permissions => {
:original => :private,
:thumb => :public_read
}
end
context "when assigned" do
setup do
before do
@file = File.new(fixture_file('5k.png'), 'rb')
@dummy = Dummy.new
@dummy.avatar = @file
end
teardown { @file.close }
after { @file.close }
context "and saved" do
setup do
before do
[:thumb, :original].each do |style|
object = stub
@dummy.avatar.stubs(:s3_object).with(style).returns(object)
......@@ -1255,7 +1255,7 @@ class S3Test < Test::Unit::TestCase
@dummy.save
end
should "succeed" do
it "succeed" do
assert true
end
end
......@@ -1263,13 +1263,13 @@ class S3Test < Test::Unit::TestCase
end
context "proc permission set" do
setup do
before do
rebuild_model(
:storage => :s3,
:bucket => "testing",
:path => ":attachment/:style/:basename.:extension",
:styles => {
:thumb => "80x80>"
:thumb => "80x80>"
},
:s3_credentials => {
'access_key_id' => "12345",
......@@ -1282,21 +1282,21 @@ class S3Test < Test::Unit::TestCase
end
context "when assigned" do
setup do
before do
@file = File.new(fixture_file('5k.png'), 'rb')
@dummy = Dummy.new
@dummy.stubs(:private_attachment? => true)
@dummy.avatar = @file
end
teardown { @file.close }
after { @file.close }
context "and saved" do
setup do
before do
@dummy.save
end
should "succeed" do
it "succeed" do
assert @dummy.avatar.url().include? "https://"
assert @dummy.avatar.url(:thumb).include? "http://"
end
......@@ -1307,7 +1307,7 @@ class S3Test < Test::Unit::TestCase
end
context "An attachment with S3 storage and metadata set using a proc as headers" do
setup do
before do
rebuild_model(
:storage => :s3,
:bucket => "testing",
......@@ -1326,17 +1326,17 @@ class S3Test < Test::Unit::TestCase
end
context "when assigned" do
setup do
before do
@file = File.new(fixture_file('5k.png'), 'rb')
@dummy = Dummy.new
@dummy.stubs(:name => 'Custom Avatar Name.png')
@dummy.avatar = @file
end
teardown { @file.close }
after { @file.close }
context "and saved" do
setup do
before do
[:thumb, :original].each do |style|
object = stub
@dummy.avatar.stubs(:s3_object).with(style).returns(object)
......@@ -1348,10 +1348,22 @@ class S3Test < Test::Unit::TestCase
@dummy.save
end
should "succeed" do
it "succeeds" do
assert true
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
# encoding: utf-8
require './test/helper'
class StyleTest < Test::Unit::TestCase
require 'spec_helper'
describe Paperclip::Style do
context "A style rule" do
setup do
before do
@attachment = attachment :path => ":basename.:extension",
:styles => { :foo => {:geometry => "100x100#", :format => :png} },
:whiny => true
@style = @attachment.styles[:foo]
end
should "be held as a Style object" do
assert_kind_of Paperclip::Style, @style
it "be held as a Style object" do
expect(@style).to be_a Paperclip::Style
end
should "get processors from the attachment definition" do
it "get processors from the attachment definition" do
assert_equal [:thumbnail], @style.processors
end
should "have the right geometry" do
it "have the right geometry" do
assert_equal "100x100#", @style.geometry
end
should "be whiny if the attachment is" do
it "be whiny if the attachment is" do
assert @style.whiny?
end
should "respond to hash notation" do
it "respond to hash notation" do
assert_equal [:thumbnail], @style[:processors]
assert_equal "100x100#", @style[:geometry]
end
......@@ -38,7 +37,7 @@ class StyleTest < Test::Unit::TestCase
end
context "A style rule with properties supplied as procs" do
setup do
before do
@attachment = attachment :path => ":basename.:extension",
:whiny_thumbnails => true,
:processors => lambda {|a| [:test]},
......@@ -52,7 +51,7 @@ class StyleTest < Test::Unit::TestCase
}
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[:bar].geometry
assert_equal [:test], @attachment.styles[:foo].processors
......@@ -63,7 +62,7 @@ class StyleTest < Test::Unit::TestCase
end
context "An attachment with style rules in various forms" do
setup do
before do
styles = {}
styles[:aslist] = ["100x100", :png]
styles[:ashash] = {:geometry => "100x100", :format => :png}
......@@ -72,36 +71,36 @@ class StyleTest < Test::Unit::TestCase
:styles => styles
end
should "have the right number of styles" do
assert_kind_of Hash, @attachment.styles
it "have the right number of styles" do
expect(@attachment.styles).to be_a Hash
assert_equal 3, @attachment.styles.size
end
should "have styles as Style objects" do
it "have styles as Style objects" do
[: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
should "have the right geometries" do
it "have the right geometries" do
[:aslist, :ashash, :aslist].each do |s|
assert_equal @attachment.styles[s].geometry, "100x100"
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[:ashash].format, :png
assert_nil @attachment.styles[:asstring].format
end
should "retain order" do
it "retain order" do
assert_equal [:aslist, :ashash, :asstring], @attachment.styles.keys
end
end
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",
:styles => {:thumb => "100x100", :large => "400x400"},
:convert_options => {:all => "-do_stuff", :thumb => "-thumbnailize"}
......@@ -109,7 +108,7 @@ class StyleTest < Test::Unit::TestCase
@style = @attachment.styles[:thumb]
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",
:styles => {:thumb => "100x100", :large => "400x400"},
:convert_options => {:all => "-do_stuff", :thumb => "-thumbnailize"}
......@@ -123,7 +122,7 @@ class StyleTest < Test::Unit::TestCase
end
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",
:styles => {:thumb => "100x100", :large => "400x400"},
:source_file_options => {:all => "-density 400", :thumb => "-depth 8"}
......@@ -131,7 +130,7 @@ class StyleTest < Test::Unit::TestCase
@style = @attachment.styles[:thumb]
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",
:styles => {:thumb => "100x100", :large => "400x400"},
:source_file_options => {:all => "-density 400", :thumb => "-depth 8"}
......@@ -145,7 +144,7 @@ class StyleTest < Test::Unit::TestCase
end
context "A style rule with its own :processors" do
setup do
before do
@attachment = attachment :path => ":basename.:extension",
:styles => {
:foo => {
......@@ -158,19 +157,19 @@ class StyleTest < Test::Unit::TestCase
@style = @attachment.styles[:foo]
end
should "not get processors from the attachment" do
it "not get processors from the attachment" do
@attachment.expects(:processors).never
assert_not_equal [:thumbnail], @style.processors
end
should "report its own processors" do
it "report its own processors" do
assert_equal [:test], @style.processors
end
end
context "A style rule with :processors supplied as procs" do
setup do
before do
@attachment = attachment :path => ":basename.:extension",
:styles => {
:foo => {
......@@ -182,17 +181,17 @@ class StyleTest < Test::Unit::TestCase
:processors => [:thumbnail]
end
should "defer processing of procs until they are needed" do
assert_kind_of Proc, @attachment.styles[:foo].instance_variable_get("@processors")
it "defer processing of procs until they are needed" do
expect(@attachment.styles[:foo].instance_variable_get("@processors")).to be_a Proc
end
should "call procs when they are needed" do
it "call procs when they are needed" do
assert_equal [:test], @attachment.styles[:foo].processors
end
end
context "An attachment with :convert_options and :source_file_options in :styles" do
setup do
before do
@attachment = attachment :path => ":basename.:extension",
:styles => {
:thumb => "100x100",
......@@ -205,19 +204,19 @@ class StyleTest < Test::Unit::TestCase
@file.stubs(:original_filename).returns("file.jpg")
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[:source_file_options]
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_extra_stuff", @attachment.styles[:large].processor_options[:source_file_options]
end
end
context "A style rule supplied with default format" do
setup do
before do
@attachment = attachment :default_format => :png,
:styles => {
:asstring => "300x300#",
......@@ -229,24 +228,24 @@ class StyleTest < Test::Unit::TestCase
}
end
should "have the right number of styles" do
assert_kind_of Hash, @attachment.styles
it "have the right number of styles" do
expect(@attachment.styles).to be_a Hash
assert_equal 3, @attachment.styles.size
end
should "have styles as Style objects" do
it "have styles as Style objects" do
[: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
should "have the right geometries" do
it "have the right geometries" do
[:aslist, :ashash, :aslist].each do |s|
assert_equal @attachment.styles[s].geometry, "300x300#"
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[:ashash].format, :png
assert_equal @attachment.styles[:asstring].format, :png
......
require './test/helper'
require 'spec_helper'
class Paperclip::TempfileFactoryTest < Test::Unit::TestCase
should "be able to generate a tempfile with the right name" do
describe Paperclip::TempfileFactory do
it "be able to generate a tempfile with the right name" do
file = subject.generate("omg.png")
assert File.extname(file.path), "png"
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")
assert File.extname(file.path), "png"
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~")
assert File.extname(file.path), "png"
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"
file = subject.generate(filename)
assert File.extname(file.path), "png"
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
assert File.exists?(file.path)
end
......
require './test/helper'
class ThumbnailTest < Test::Unit::TestCase
require 'spec_helper'
describe Paperclip::Thumbnail do
context "A Paperclip Tempfile" do
setup do
before do
@tempfile = Paperclip::Tempfile.new(["file", ".jpg"])
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)
end
should "be a real Tempfile" do
it "be a real Tempfile" do
assert @tempfile.is_a?(::Tempfile)
end
end
context "Another Paperclip Tempfile" do
setup do
before do
@tempfile = Paperclip::Tempfile.new("file")
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)
end
should "still be a real Tempfile" do
it "still be a real Tempfile" do
assert @tempfile.is_a?(::Tempfile)
end
end
context "An image" do
setup do
before do
@file = File.new(fixture_file("5k.png"), 'rb')
end
teardown { @file.close }
after { @file.close }
[["600x600>", "434x66"],
["400x400>", "400x61"],
["32x32<", "434x66"]
].each do |args|
context "being thumbnailed with a geometry of #{args[0]}" do
setup do
before do
@thumb = Paperclip::Thumbnail.new(@file, :geometry => args[0])
end
should "start with dimensions of 434x66" do
it "start with dimensions of 434x66" do
cmd = %Q[identify -format "%wx%h" "#{@file.path}"]
assert_equal "434x66", `#{cmd}`.chomp
end
should "report the correct target geometry" do
it "report the correct target geometry" do
assert_equal args[0], @thumb.target_geometry.to_s
end
context "when made" do
setup do
before do
@thumb_result = @thumb.make
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}"]
assert_equal args[1], `#{cmd}`.chomp
end
......@@ -73,11 +72,11 @@ class ThumbnailTest < Test::Unit::TestCase
end
context "being thumbnailed at 100x50 with cropping" do
setup do
before do
@thumb = Paperclip::Thumbnail.new(@file, :geometry => "100x50#")
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']
begin
Cocaine::CommandLine.path = ''
......@@ -93,28 +92,28 @@ class ThumbnailTest < Test::Unit::TestCase
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 "434x66", @thumb.current_geometry.to_s
end
should "report its correct format" do
it "report its correct format" do
assert_nil @thumb.format
end
should "have whiny turned on by default" do
it "have whiny turned on by default" do
assert @thumb.whiny
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
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
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|
arg[0] == ':source -auto-orient -resize "x50" -crop "100x50+114+0" +repage :dest' &&
arg[1][:source] == "#{File.expand_path(@thumb.file.path)}[0]"
......@@ -122,13 +121,13 @@ class ThumbnailTest < Test::Unit::TestCase
@thumb.make
end
should "create the thumbnail when sent #make" do
it "create the thumbnail when sent #make" do
dst = @thumb.make
assert_match /100x50/, `identify "#{dst.path}"`
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'))
thumb = Paperclip::Thumbnail.new(file, :geometry => "50x50#")
......@@ -139,17 +138,17 @@ class ThumbnailTest < Test::Unit::TestCase
end
context "being thumbnailed with source file options set" do
setup do
before do
@thumb = Paperclip::Thumbnail.new(@file,
:geometry => "100x50#",
:source_file_options => "-strip")
end
should "have source_file_options value set" do
it "have source_file_options value set" do
assert_equal ["-strip"], @thumb.source_file_options
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|
arg[0] == '-strip :source -auto-orient -resize "x50" -crop "100x50+114+0" +repage :dest' &&
arg[1][:source] == "#{File.expand_path(@thumb.file.path)}[0]"
......@@ -157,19 +156,19 @@ class ThumbnailTest < Test::Unit::TestCase
@thumb.make
end
should "create the thumbnail when sent #make" do
it "create the thumbnail when sent #make" do
dst = @thumb.make
assert_match /100x50/, `identify "#{dst.path}"`
end
context "redefined to have bad source_file_options setting" do
setup do
before do
@thumb = Paperclip::Thumbnail.new(@file,
:geometry => "100x50#",
:source_file_options => "-this-aint-no-option")
end
should "error when trying to create the thumbnail" do
it "error when trying to create the thumbnail" do
assert_raises(Paperclip::Error) do
silence_stream(STDERR) do
@thumb.make
......@@ -180,17 +179,17 @@ class ThumbnailTest < Test::Unit::TestCase
end
context "being thumbnailed with convert options set" do
setup do
before do
@thumb = Paperclip::Thumbnail.new(@file,
:geometry => "100x50#",
:convert_options => "-strip -depth 8")
end
should "have convert_options value set" do
it "have convert_options value set" do
assert_equal %w"-strip -depth 8", @thumb.convert_options
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|
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]"
......@@ -198,19 +197,19 @@ class ThumbnailTest < Test::Unit::TestCase
@thumb.make
end
should "create the thumbnail when sent #make" do
it "create the thumbnail when sent #make" do
dst = @thumb.make
assert_match /100x50/, `identify "#{dst.path}"`
end
context "redefined to have bad convert_options setting" do
setup do
before do
@thumb = Paperclip::Thumbnail.new(@file,
:geometry => "100x50#",
:convert_options => "-this-aint-no-option")
end
should "error when trying to create the thumbnail" do
it "error when trying to create the thumbnail" do
assert_raises(Paperclip::Error) do
silence_stream(STDERR) do
@thumb.make
......@@ -218,7 +217,7 @@ class ThumbnailTest < Test::Unit::TestCase
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']
begin
Cocaine::CommandLine.path = ''
......@@ -237,19 +236,19 @@ class ThumbnailTest < Test::Unit::TestCase
end
context "being thumbnailed with a blank geometry string" do
setup do
before do
@thumb = Paperclip::Thumbnail.new(@file,
:geometry => "",
:convert_options => "-gravity center -crop \"300x300+0-0\"")
end
should "not get resized by default" do
it "not get resized by default" do
assert !@thumb.transformation_command.include?("-resize")
end
end
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.expects(:identify).at_least_once.with do |*arg|
arg[0] == '-format %m :file' &&
......@@ -260,11 +259,11 @@ class ThumbnailTest < Test::Unit::TestCase
end
context "passing a custom file geometry parser" do
teardown do
self.class.send(:remove_const, :GeoParser)
after do
Object.send(:remove_const, :GeoParser)
end
should "produce the appropriate transformation_command" do
it "produce the appropriate transformation_command" do
GeoParser = Class.new do
def self.from_file(file)
new
......@@ -275,7 +274,7 @@ class ThumbnailTest < Test::Unit::TestCase
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
......@@ -291,11 +290,11 @@ class ThumbnailTest < Test::Unit::TestCase
end
context "passing a custom geometry string parser" do
teardown do
self.class.send(:remove_const, :GeoParser)
after do
Object.send(:remove_const, :GeoParser)
end
should "produce the appropriate transformation_command" do
it "produce the appropriate transformation_command" do
GeoParser = Class.new do
def self.parse(s)
new
......@@ -306,7 +305,7 @@ class ThumbnailTest < Test::Unit::TestCase
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
......@@ -317,32 +316,32 @@ class ThumbnailTest < Test::Unit::TestCase
end
context "A multipage PDF" do
setup do
before do
@file = File.new(fixture_file("twopage.pdf"), 'rb')
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}"]
assert_equal "612x792"*2, `#{cmd}`.chomp
end
context "being thumbnailed at 100x100 with cropping" do
setup do
before do
@thumb = Paperclip::Thumbnail.new(@file, :geometry => "100x100#", :format => :png)
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 "612x792", @thumb.current_geometry.to_s
end
should "report its correct format" do
it "report its correct format" do
assert_equal :png, @thumb.format
end
should "create the thumbnail when sent #make" do
it "create the thumbnail when sent #make" do
dst = @thumb.make
assert_match /100x100/, `identify "#{dst.path}"`
end
......@@ -350,23 +349,23 @@ class ThumbnailTest < Test::Unit::TestCase
end
context "An animated gif" do
setup do
before do
@file = File.new(fixture_file("animated.gif"), 'rb')
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}"]
assert_equal "100x100"*12, `#{cmd}`.chomp
end
context "with static output" do
setup do
before do
@thumb = Paperclip::Thumbnail.new(@file, :geometry => "50x50", :format => :jpg)
end
should "create the single frame thumbnail when sent #make" do
it "create the single frame thumbnail when sent #make" do
dst = @thumb.make
cmd = %Q[identify -format "%wx%h" "#{dst.path}"]
assert_equal "50x50", `#{cmd}`.chomp
......@@ -374,11 +373,11 @@ class ThumbnailTest < Test::Unit::TestCase
end
context "with animated output format" do
setup do
before do
@thumb = Paperclip::Thumbnail.new(@file, :geometry => "50x50", :format => :gif)
end
should "create the 12 frames thumbnail when sent #make" do
it "create the 12 frames thumbnail when sent #make" do
dst = @thumb.make
cmd = %Q[identify -format "%wx%h," "#{dst.path}"]
frames = `#{cmd}`.chomp.split(',')
......@@ -386,21 +385,21 @@ class ThumbnailTest < Test::Unit::TestCase
assert_frame_dimensions (45..50), frames
end
should "use the -coalesce option" do
it "use the -coalesce option" do
assert_equal @thumb.transformation_command.first, "-coalesce"
end
should "use the -layers 'optimize' option" do
it "use the -layers 'optimize' option" do
assert_equal @thumb.transformation_command.last, '-layers "optimize"'
end
end
context "with omitted output format" do
setup do
before do
@thumb = Paperclip::Thumbnail.new(@file, :geometry => "50x50")
end
should "create the 12 frames thumbnail when sent #make" do
it "create the 12 frames thumbnail when sent #make" do
dst = @thumb.make
cmd = %Q[identify -format "%wx%h," "#{dst.path}"]
frames = `#{cmd}`.chomp.split(',')
......@@ -408,22 +407,22 @@ class ThumbnailTest < Test::Unit::TestCase
assert_frame_dimensions (45..50), frames
end
should "use the -coalesce option" do
it "use the -coalesce option" do
assert_equal @thumb.transformation_command.first, "-coalesce"
end
should "use the -layers 'optimize' option" do
it "use the -layers 'optimize' option" do
assert_equal @thumb.transformation_command.last, '-layers "optimize"'
end
end
context "with unidentified source format" do
setup do
before do
@unidentified_file = File.new(fixture_file("animated.unknown"), 'rb')
@thumb = Paperclip::Thumbnail.new(@file, :geometry => "60x60")
end
should "create the 12 frames thumbnail when sent #make" do
it "create the 12 frames thumbnail when sent #make" do
dst = @thumb.make
cmd = %Q[identify -format "%wx%h," "#{dst.path}"]
frames = `#{cmd}`.chomp.split(',')
......@@ -431,22 +430,22 @@ class ThumbnailTest < Test::Unit::TestCase
assert_frame_dimensions (55..60), frames
end
should "use the -coalesce option" do
it "use the -coalesce option" do
assert_equal @thumb.transformation_command.first, "-coalesce"
end
should "use the -layers 'optimize' option" do
it "use the -layers 'optimize' option" do
assert_equal @thumb.transformation_command.last, '-layers "optimize"'
end
end
context "with no source format" do
setup do
before do
@unidentified_file = File.new(fixture_file("animated"), 'rb')
@thumb = Paperclip::Thumbnail.new(@file, :geometry => "70x70")
end
should "create the 12 frames thumbnail when sent #make" do
it "create the 12 frames thumbnail when sent #make" do
dst = @thumb.make
cmd = %Q[identify -format "%wx%h," "#{dst.path}"]
frames = `#{cmd}`.chomp.split(',')
......@@ -454,27 +453,27 @@ class ThumbnailTest < Test::Unit::TestCase
assert_frame_dimensions (60..70), frames
end
should "use the -coalesce option" do
it "use the -coalesce option" do
assert_equal @thumb.transformation_command.first, "-coalesce"
end
should "use the -layers 'optimize' option" do
it "use the -layers 'optimize' option" do
assert_equal @thumb.transformation_command.last, '-layers "optimize"'
end
end
context "with animated option set to false" do
setup do
before do
@thumb = Paperclip::Thumbnail.new(@file, :geometry => "50x50", :animated => false)
end
should "output the gif format" do
it "output the gif format" do
dst = @thumb.make
cmd = %Q[identify "#{dst.path}"]
assert_match /GIF/, `#{cmd}`.chomp
end
should "create the single frame thumbnail when sent #make" do
it "create the single frame thumbnail when sent #make" do
dst = @thumb.make
cmd = %Q[identify -format "%wx%h" "#{dst.path}"]
assert_equal "50x50", `#{cmd}`.chomp
......
# encoding: utf-8
require './test/helper'
require 'paperclip/url_generator'
require 'spec_helper'
class UrlGeneratorTest < Test::Unit::TestCase
should "use the given interpolator" do
describe Paperclip::UrlGenerator do
it "use the given interpolator" do
expected = "the expected result"
mock_attachment = MockAttachment.new
mock_interpolator = MockInterpolator.new(:result => expected)
......@@ -17,7 +16,7 @@ class UrlGeneratorTest < Test::Unit::TestCase
assert mock_interpolator.has_interpolated_style_name?(:style_name)
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_interpolator = MockInterpolator.new
default_url = "the default url"
......@@ -30,7 +29,7 @@ class UrlGeneratorTest < Test::Unit::TestCase
"expected the interpolator to be passed #{default_url.inspect} but it wasn't"
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_interpolator = MockInterpolator.new
default_url = lambda {|attachment| "the #{attachment.class.name} default url" }
......@@ -43,7 +42,7 @@ class UrlGeneratorTest < Test::Unit::TestCase
%{expected the interpolator to be passed "the MockAttachment default url", but it wasn't}
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_attachment = MockAttachment.new(:model => mock_model)
mock_interpolator = MockInterpolator.new
......@@ -57,7 +56,7 @@ class UrlGeneratorTest < Test::Unit::TestCase
%{expected the interpolator to be passed #{mock_model.to_s}, but it wasn't}
end
should "URL-escape spaces if asked to" do
it "URL-escape spaces if asked to" do
expected = "the expected result"
mock_attachment = MockAttachment.new
mock_interpolator = MockInterpolator.new(:result => expected)
......@@ -69,7 +68,7 @@ class UrlGeneratorTest < Test::Unit::TestCase
assert_equal "the%20expected%20result", result
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
def escape
"the escaped result"
......@@ -85,7 +84,7 @@ class UrlGeneratorTest < Test::Unit::TestCase
assert_equal "the escaped result", result
end
should "leave spaces unescaped as asked to" do
it "leave spaces unescaped as asked to" do
expected = "the expected result"
mock_attachment = MockAttachment.new
mock_interpolator = MockInterpolator.new(:result => expected)
......@@ -97,7 +96,7 @@ class UrlGeneratorTest < Test::Unit::TestCase
assert_equal "the expected result", result
end
should "default to leaving spaces unescaped" do
it "default to leaving spaces unescaped" do
expected = "the expected result"
mock_attachment = MockAttachment.new
mock_interpolator = MockInterpolator.new(:result => expected)
......@@ -109,7 +108,7 @@ class UrlGeneratorTest < Test::Unit::TestCase
assert_equal "the expected result", result
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"
mock_interpolator = MockInterpolator.new(:result => expected)
mock_attachment = MockAttachment.new(:responds_to_updated_at => false)
......@@ -121,7 +120,7 @@ class UrlGeneratorTest < Test::Unit::TestCase
assert_equal expected, result
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"
mock_interpolator = MockInterpolator.new(:result => expected)
mock_attachment = MockAttachment.new(:responds_to_updated_at => true, :updated_at => nil)
......@@ -133,7 +132,7 @@ class UrlGeneratorTest < Test::Unit::TestCase
assert_equal expected, result
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"
updated_at = 1231231234
mock_interpolator = MockInterpolator.new(:result => expected)
......@@ -146,7 +145,7 @@ class UrlGeneratorTest < Test::Unit::TestCase
assert_equal "#{expected}?#{updated_at}", result
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"
updated_at = 1231231234
mock_interpolator = MockInterpolator.new(:result => expected)
......@@ -159,7 +158,7 @@ class UrlGeneratorTest < Test::Unit::TestCase
assert_equal "#{expected}&#{updated_at}", result
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"
updated_at = 1231231234
mock_interpolator = MockInterpolator.new(:result => expected)
......@@ -172,7 +171,7 @@ class UrlGeneratorTest < Test::Unit::TestCase
assert_equal expected, result
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"
mock_attachment = MockAttachment.new(:original_filename => 'exists')
mock_interpolator = MockInterpolator.new
......
require './test/helper'
require 'spec_helper'
class AttachmentContentTypeValidatorTest < Test::Unit::TestCase
def setup
describe Paperclip::Validators::AttachmentContentTypeValidator do
before do
rebuild_model
@dummy = Dummy.new
super
end
def build_validator(options)
......@@ -14,69 +13,68 @@ class AttachmentContentTypeValidatorTest < Test::Unit::TestCase
end
context "with a nil content type" do
setup do
before do
build_validator :content_type => "image/jpg"
@dummy.stubs(:avatar_content_type => nil)
@validator.validate(@dummy)
end
should "not set an error message" do
it "not set an error message" do
assert @dummy.errors[:avatar_content_type].blank?
end
end
context "with :allow_nil option" do
context "as true" do
setup do
before do
build_validator :content_type => "image/png", :allow_nil => true
@dummy.stubs(:avatar_content_type => nil)
@validator.validate(@dummy)
end
should "allow avatar_content_type as nil" do
it "allow avatar_content_type as nil" do
assert @dummy.errors[:avatar_content_type].blank?
end
end
context "as false" do
setup do
before do
build_validator :content_type => "image/png", :allow_nil => false
@dummy.stubs(:avatar_content_type => nil)
@validator.validate(@dummy)
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?
end
end
end
context "with a failing validation" do
setup do
before do
build_validator :content_type => "image/png", :allow_nil => false
@dummy.stubs(:avatar_content_type => nil)
@validator.validate(@dummy)
end
should "add error to the base object" do
it "add error to the base object" do
assert @dummy.errors[:avatar].present?,
"Error not added to base attribute"
end
should "add error to base object as a string" do
assert_kind_of String, @dummy.errors[:avatar].first,
"Error added to base attribute as something other than a String"
it "add error to base object as a string" do
expect(@dummy.errors[:avatar].first).to be_a String
end
end
context "with a successful validation" do
setup do
before do
build_validator :content_type => "image/png", :allow_nil => false
@dummy.stubs(:avatar_content_type => "image/png")
@validator.validate(@dummy)
end
should "not add error to the base object" do
it "not add error to the base object" do
assert @dummy.errors[:avatar].blank?,
"Error was added to base attribute"
end
......@@ -84,25 +82,25 @@ class AttachmentContentTypeValidatorTest < Test::Unit::TestCase
context "with :allow_blank option" do
context "as true" do
setup do
before do
build_validator :content_type => "image/png", :allow_blank => true
@dummy.stubs(:avatar_content_type => "")
@validator.validate(@dummy)
end
should "allow avatar_content_type as blank" do
it "allow avatar_content_type as blank" do
assert @dummy.errors[:avatar_content_type].blank?
end
end
context "as false" do
setup do
before do
build_validator :content_type => "image/png", :allow_blank => false
@dummy.stubs(:avatar_content_type => "")
@validator.validate(@dummy)
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?
end
end
......@@ -111,37 +109,37 @@ class AttachmentContentTypeValidatorTest < Test::Unit::TestCase
context "whitelist format" do
context "with an allowed type" do
context "as a string" do
setup do
before do
build_validator :content_type => "image/jpg"
@dummy.stubs(:avatar_content_type => "image/jpg")
@validator.validate(@dummy)
end
should "not set an error message" do
it "not set an error message" do
assert @dummy.errors[:avatar_content_type].blank?
end
end
context "as an regexp" do
setup do
before do
build_validator :content_type => /^image\/.*/
@dummy.stubs(:avatar_content_type => "image/jpg")
@validator.validate(@dummy)
end
should "not set an error message" do
it "not set an error message" do
assert @dummy.errors[:avatar_content_type].blank?
end
end
context "as a list" do
setup do
before do
build_validator :content_type => ["image/png", "image/jpg", "image/jpeg"]
@dummy.stubs(:avatar_content_type => "image/jpg")
@validator.validate(@dummy)
end
should "not set an error message" do
it "not set an error message" do
assert @dummy.errors[:avatar_content_type].blank?
end
end
......@@ -149,53 +147,53 @@ class AttachmentContentTypeValidatorTest < Test::Unit::TestCase
context "with a disallowed type" do
context "as a string" do
setup do
before do
build_validator :content_type => "image/png"
@dummy.stubs(:avatar_content_type => "image/jpg")
@validator.validate(@dummy)
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_includes @dummy.errors[:avatar_content_type], "is invalid"
expect(@dummy.errors[:avatar_content_type]).to include "is invalid"
end
end
context "as a regexp" do
setup do
before do
build_validator :content_type => /^text\/.*/
@dummy.stubs(:avatar_content_type => "image/jpg")
@validator.validate(@dummy)
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_includes @dummy.errors[:avatar_content_type], "is invalid"
expect(@dummy.errors[:avatar_content_type]).to include "is invalid"
end
end
context "with :message option" do
context "without interpolation" do
setup do
before do
build_validator :content_type => "image/png", :message => "should be a PNG image"
@dummy.stubs(:avatar_content_type => "image/jpg")
@validator.validate(@dummy)
end
should "set a correct error message" do
assert_includes @dummy.errors[:avatar_content_type], "should be a PNG image"
it "set a correct error message" do
expect(@dummy.errors[:avatar_content_type]).to include "should be a PNG image"
end
end
context "with interpolation" do
setup do
before do
build_validator :content_type => "image/png", :message => "should have content type %{types}"
@dummy.stubs(:avatar_content_type => "image/jpg")
@validator.validate(@dummy)
end
should "set a correct error message" do
assert_includes @dummy.errors[:avatar_content_type], "should have content type image/png"
it "set a correct error message" do
expect(@dummy.errors[:avatar_content_type]).to include "should have content type image/png"
end
end
end
......@@ -205,37 +203,37 @@ class AttachmentContentTypeValidatorTest < Test::Unit::TestCase
context "blacklist format" do
context "with an allowed type" do
context "as a string" do
setup do
before do
build_validator :not => "image/gif"
@dummy.stubs(:avatar_content_type => "image/jpg")
@validator.validate(@dummy)
end
should "not set an error message" do
it "not set an error message" do
assert @dummy.errors[:avatar_content_type].blank?
end
end
context "as an regexp" do
setup do
before do
build_validator :not => /^text\/.*/
@dummy.stubs(:avatar_content_type => "image/jpg")
@validator.validate(@dummy)
end
should "not set an error message" do
it "not set an error message" do
assert @dummy.errors[:avatar_content_type].blank?
end
end
context "as a list" do
setup do
before do
build_validator :not => ["image/png", "image/jpg", "image/jpeg"]
@dummy.stubs(:avatar_content_type => "image/gif")
@validator.validate(@dummy)
end
should "not set an error message" do
it "not set an error message" do
assert @dummy.errors[:avatar_content_type].blank?
end
end
......@@ -243,53 +241,53 @@ class AttachmentContentTypeValidatorTest < Test::Unit::TestCase
context "with a disallowed type" do
context "as a string" do
setup do
before do
build_validator :not => "image/png"
@dummy.stubs(:avatar_content_type => "image/png")
@validator.validate(@dummy)
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_includes @dummy.errors[:avatar_content_type], "is invalid"
expect(@dummy.errors[:avatar_content_type]).to include "is invalid"
end
end
context "as a regexp" do
setup do
before do
build_validator :not => /^text\/.*/
@dummy.stubs(:avatar_content_type => "text/plain")
@validator.validate(@dummy)
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_includes @dummy.errors[:avatar_content_type], "is invalid"
expect(@dummy.errors[:avatar_content_type]).to include "is invalid"
end
end
context "with :message option" do
context "without interpolation" do
setup do
before do
build_validator :not => "image/png", :message => "should not be a PNG image"
@dummy.stubs(:avatar_content_type => "image/png")
@validator.validate(@dummy)
end
should "set a correct error message" do
assert_includes @dummy.errors[:avatar_content_type], "should not be a PNG image"
it "set a correct error message" do
expect(@dummy.errors[:avatar_content_type]).to include "should not be a PNG image"
end
end
context "with interpolation" do
setup do
before do
build_validator :not => "image/png", :message => "should not have content type %{types}"
@dummy.stubs(:avatar_content_type => "image/png")
@validator.validate(@dummy)
end
should "set a correct error message" do
assert_includes @dummy.errors[:avatar_content_type], "should not have content type image/png"
it "set a correct error message" do
expect(@dummy.errors[:avatar_content_type]).to include "should not have content type image/png"
end
end
end
......@@ -297,27 +295,27 @@ class AttachmentContentTypeValidatorTest < Test::Unit::TestCase
end
context "using the helper" do
setup do
before do
Dummy.validates_attachment_content_type :avatar, :content_type => "image/jpg"
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 }
end
end
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
build_validator :message => "Some message"
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"
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"
end
end
......
require './test/helper'
require 'spec_helper'
class AttachmentFileNameValidatorTest < Test::Unit::TestCase
def setup
describe Paperclip::Validators::AttachmentFileNameValidator do
before do
rebuild_model
@dummy = Dummy.new
super
end
def build_validator(options)
......@@ -14,24 +13,23 @@ class AttachmentFileNameValidatorTest < Test::Unit::TestCase
end
context "with a failing validation" do
setup do
before do
build_validator :matches => /.*\.png$/, :allow_nil => false
@dummy.stubs(:avatar_file_name => "data.txt")
@validator.validate(@dummy)
end
should "add error to the base object" do
it "add error to the base object" do
assert @dummy.errors[:avatar].present?,
"Error not added to base attribute"
end
should "add error to base object as a string" do
assert_kind_of String, @dummy.errors[:avatar].first,
"Error added to base attribute as something other than a String"
it "add error to base object as a string" do
expect(@dummy.errors[:avatar].first).to be_a String
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
@dummy.stubs(:avatar_file_name => "image.png")
@validator.validate(@dummy)
......@@ -42,46 +40,46 @@ class AttachmentFileNameValidatorTest < Test::Unit::TestCase
context "whitelist format" do
context "with an allowed type" do
context "as a single regexp" do
setup do
before do
build_validator :matches => /.*\.jpg$/
@dummy.stubs(:avatar_file_name => "image.jpg")
@validator.validate(@dummy)
end
should "not set an error message" do
it "not set an error message" do
assert @dummy.errors[:avatar_file_name].blank?
end
end
context "as a list" do
setup do
before do
build_validator :matches => [/.*\.png$/, /.*\.jpe?g$/]
@dummy.stubs(:avatar_file_name => "image.jpg")
@validator.validate(@dummy)
end
should "not set an error message" do
it "not set an error message" do
assert @dummy.errors[:avatar_file_name].blank?
end
end
end
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\/.*/
@dummy.stubs(:avatar_file_name => "image.jpg")
@validator.validate(@dummy)
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
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"
@dummy.stubs(:avatar_file_name => "image.jpg")
@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
......@@ -89,72 +87,72 @@ class AttachmentFileNameValidatorTest < Test::Unit::TestCase
context "blacklist format" do
context "with an allowed type" do
context "as a single regexp" do
setup do
before do
build_validator :not => /^text\/.*/
@dummy.stubs(:avatar_file_name => "image.jpg")
@validator.validate(@dummy)
end
should "not set an error message" do
it "not set an error message" do
assert @dummy.errors[:avatar_file_name].blank?
end
end
context "as a list" do
setup do
before do
build_validator :not => [/.*\.png$/, /.*\.jpe?g$/]
@dummy.stubs(:avatar_file_name => "image.gif")
@validator.validate(@dummy)
end
should "not set an error message" do
it "not set an error message" do
assert @dummy.errors[:avatar_file_name].blank?
end
end
end
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.*/
@dummy.stubs(:avatar_file_name => "data.txt")
@validator.validate(@dummy)
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
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"
@dummy.stubs(:avatar_file_name => "image.png")
@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
context "using the helper" do
setup do
before do
Dummy.validates_attachment_file_name :avatar, :matches => /.*\.jpg$/
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 }
end
end
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
build_validator :message => "Some message"
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$/
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$/
end
end
......
require './test/helper'
require 'spec_helper'
class AttachmentPresenceValidatorTest < Test::Unit::TestCase
def setup
describe Paperclip::Validators::AttachmentPresenceValidator do
before do
rebuild_model
@dummy = Dummy.new
end
......@@ -13,44 +13,44 @@ class AttachmentPresenceValidatorTest < Test::Unit::TestCase
end
context "nil attachment" do
setup do
before do
@dummy.avatar = nil
end
context "with default options" do
setup do
before do
build_validator
@validator.validate(@dummy)
end
should "add error on the attachment" do
it "add error on the attachment" do
assert @dummy.errors[:avatar].present?
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?
end
end
context "with :if option" do
context "returning true" do
setup do
before do
build_validator :if => true
@validator.validate(@dummy)
end
should "perform a validation" do
it "perform a validation" do
assert @dummy.errors[:avatar].present?
end
end
context "returning false" do
setup do
before do
build_validator :if => false
@validator.validate(@dummy)
end
should "perform a validation" do
it "perform a validation" do
assert @dummy.errors[:avatar].present?
end
end
......@@ -58,27 +58,27 @@ class AttachmentPresenceValidatorTest < Test::Unit::TestCase
end
context "with attachment" do
setup do
before do
build_validator
@dummy.avatar = StringIO.new('.\n')
@validator.validate(@dummy)
end
should "not add error on the attachment" do
it "not add error on the attachment" do
assert @dummy.errors[:avatar].blank?
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?
end
end
context "using the helper" do
setup do
before do
Dummy.validates_attachment_presence :avatar
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 }
end
end
......
require './test/helper'
require 'spec_helper'
class AttachmentSizeValidatorTest < Test::Unit::TestCase
def setup
describe Paperclip::Validators::AttachmentSizeValidator do
before do
rebuild_model
@dummy = Dummy.new
end
......@@ -14,14 +14,14 @@ class AttachmentSizeValidatorTest < Test::Unit::TestCase
def self.should_allow_attachment_file_size(size)
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)
@validator.validate(@dummy)
assert @dummy.errors[:avatar_file_size].blank?,
"Expect an error message on :avatar_file_size, got none."
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?,
"Error added to base attribute"
end
......@@ -30,29 +30,28 @@ class AttachmentSizeValidatorTest < Test::Unit::TestCase
def self.should_not_allow_attachment_file_size(size, options = {})
context "when the attachment size is #{size}" do
setup do
before do
@dummy.stubs(:avatar_file_size).returns(size)
@validator.validate(@dummy)
end
should "add error to dummy object" do
it "add error to dummy object" do
assert @dummy.errors[:avatar_file_size].present?,
"Unexpected error message on :avatar_file_size"
end
should "add error to the base dummy object" do
it "add error to the base dummy object" do
assert @dummy.errors[:avatar].present?,
"Error not added to base attribute"
end
should "add error to base object as a string" do
assert_kind_of String, @dummy.errors[:avatar].first,
"Error added to base attribute as something other than a String"
it "add error to base object as a string" do
expect(@dummy.errors[:avatar].first).to be_a String
end
if options[:message]
should "return a correct error message" do
assert_includes @dummy.errors[:avatar_file_size], options[:message]
it "return a correct error message" do
expect(@dummy.errors[:avatar_file_size]).to include options[:message]
end
end
end
......@@ -60,7 +59,7 @@ class AttachmentSizeValidatorTest < Test::Unit::TestCase
context "with :in option" do
context "as a range" do
setup do
before do
build_validator :in => (5.kilobytes..10.kilobytes)
end
......@@ -70,7 +69,7 @@ class AttachmentSizeValidatorTest < Test::Unit::TestCase
end
context "as a proc" do
setup do
before do
build_validator :in => lambda { |avatar| (5.kilobytes..10.kilobytes) }
end
......@@ -82,7 +81,7 @@ class AttachmentSizeValidatorTest < Test::Unit::TestCase
context "with :greater_than option" do
context "as number" do
setup do
before do
build_validator :greater_than => 10.kilobytes
end
......@@ -91,7 +90,7 @@ class AttachmentSizeValidatorTest < Test::Unit::TestCase
end
context "as a proc" do
setup do
before do
build_validator :greater_than => lambda { |avatar| 10.kilobytes }
end
......@@ -102,7 +101,7 @@ class AttachmentSizeValidatorTest < Test::Unit::TestCase
context "with :less_than option" do
context "as number" do
setup do
before do
build_validator :less_than => 10.kilobytes
end
......@@ -111,7 +110,7 @@ class AttachmentSizeValidatorTest < Test::Unit::TestCase
end
context "as a proc" do
setup do
before do
build_validator :less_than => lambda { |avatar| 10.kilobytes }
end
......@@ -122,7 +121,7 @@ class AttachmentSizeValidatorTest < Test::Unit::TestCase
context "with :greater_than and :less_than option" do
context "as numbers" do
setup do
before do
build_validator :greater_than => 5.kilobytes,
:less_than => 10.kilobytes
end
......@@ -133,7 +132,7 @@ class AttachmentSizeValidatorTest < Test::Unit::TestCase
end
context "as a proc" do
setup do
before do
build_validator :greater_than => lambda { |avatar| 5.kilobytes },
:less_than => lambda { |avatar| 10.kilobytes }
end
......@@ -146,7 +145,7 @@ class AttachmentSizeValidatorTest < Test::Unit::TestCase
context "with :message option" do
context "given a range" do
setup do
before do
build_validator :in => (5.kilobytes..10.kilobytes),
:message => "is invalid. (Between %{min} and %{max} please.)"
end
......@@ -156,7 +155,7 @@ class AttachmentSizeValidatorTest < Test::Unit::TestCase
end
context "given :less_than and :greater_than" do
setup do
before do
build_validator :less_than => 10.kilobytes,
:greater_than => 5.kilobytes,
:message => "is invalid. (Between %{min} and %{max} please.)"
......@@ -169,7 +168,7 @@ class AttachmentSizeValidatorTest < Test::Unit::TestCase
context "default error messages" do
context "given :less_than and :greater_than" do
setup do
before do
build_validator :greater_than => 5.kilobytes,
:less_than => 10.kilobytes
end
......@@ -181,7 +180,7 @@ class AttachmentSizeValidatorTest < Test::Unit::TestCase
end
context "given a size range" do
setup do
before do
build_validator :in => (5.kilobytes..10.kilobytes)
end
......@@ -193,29 +192,29 @@ class AttachmentSizeValidatorTest < Test::Unit::TestCase
end
context "using the helper" do
setup do
before do
Dummy.validates_attachment_size :avatar, :in => (5.kilobytes..10.kilobytes)
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 }
end
end
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
build_validator :message => "Some message"
end
end
(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
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)
end
end
......
require './test/helper'
require 'spec_helper'
class MediaTypeSpoofDetectionValidatorTest < Test::Unit::TestCase
def setup
describe Paperclip::Validators::MediaTypeSpoofDetectionValidator do
before do
rebuild_model
@dummy = Dummy.new
end
......@@ -12,11 +12,11 @@ class MediaTypeSpoofDetectionValidatorTest < Test::Unit::TestCase
))
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 }
end
should "return default error message for spoofed media type" do
it "return default error message for spoofed media type" do
build_validator
file = File.new(fixture_file("5k.png"), "rb")
@dummy.avatar.assign(file)
......@@ -28,7 +28,7 @@ class MediaTypeSpoofDetectionValidatorTest < Test::Unit::TestCase
assert_equal "has an extension that does not match its contents", @dummy.errors[:avatar].first
end
should "run when attachment is dirty" do
it "run when attachment is dirty" do
build_validator
file = File.new(fixture_file("5k.png"), "rb")
@dummy.avatar.assign(file)
......@@ -39,7 +39,7 @@ class MediaTypeSpoofDetectionValidatorTest < Test::Unit::TestCase
assert_received(Paperclip::MediaTypeSpoofDetector, :using){|e| e.once }
end
should "not run when attachment is not dirty" do
it "not run when attachment is not dirty" do
Paperclip::MediaTypeSpoofDetector.stubs(:using).never
@dummy.valid?
assert_received(Paperclip::MediaTypeSpoofDetector, :using){|e| e.never }
......
require './test/helper'
class ValidatorsTest < Test::Unit::TestCase
include ActiveSupport::Testing::Deprecation
def setup
rebuild_model
end
require 'spec_helper'
describe Paperclip::Validators do
context "using the helper" do
setup do
Dummy.validates_attachment :avatar, :presence => true, :content_type => { :content_type => "image/jpeg" }, :size => { :in => 0..10.kilobytes }
before do
Dummy.validates_attachment :avatar, :presence => true, :content_type => { :content_type => "image/jpeg" }, :size => { :in => 0..10240 }
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 }
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 }
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 }
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 = Dummy.new(:avatar => File.new(fixture_file("12k.png")))
assert_equal [:avatar_content_type, :avatar, :avatar_file_size], dummy.errors.keys
assert_raise(RuntimeError){ dummy.valid? }
assert_raises(RuntimeError){ dummy.valid? }
end
end
context "using the helper with a conditional" do
setup do
before do
rebuild_class
Dummy.validates_attachment :avatar, :presence => true,
:content_type => { :content_type => "image/jpeg" },
:size => { :in => 0..10.kilobytes },
:size => { :in => 0..10240 },
:if => :title_present?
end
should "validate the attachment if title is present" do
it "validates the attachment if title is present" do
Dummy.class_eval do
def title_present?
true
......@@ -50,50 +45,50 @@ class ValidatorsTest < Test::Unit::TestCase
assert_equal [:avatar_content_type, :avatar, :avatar_file_size], dummy.errors.keys
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
def title_present?
false
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
end
end
context 'with no other validations on the Dummy#avatar attachment' do
setup do
before do
reset_class("Dummy")
Dummy.has_attached_file :avatar
Paperclip.reset_duplicate_clash_check!
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
Dummy.new(:avatar => File.new(fixture_file("12k.png")))
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" }
assert_nothing_raised(Paperclip::Errors::MissingRequiredValidatorError) do
assert_nothing_raised do
Dummy.new(:avatar => File.new(fixture_file("12k.png")))
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$/ }
assert_nothing_raised(Paperclip::Errors::MissingRequiredValidatorError) do
assert_nothing_raised do
Dummy.new(:avatar => File.new(fixture_file("12k.png")))
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
assert_nothing_raised(Paperclip::Errors::MissingRequiredValidatorError) do
assert_nothing_raised do
Dummy.new(:avatar => File.new(fixture_file("12k.png")))
end
end
......
require 'rubygems'
require 'tempfile'
require 'pathname'
require 'test/unit'
require 'rspec'
require 'active_record'
require 'active_record/version'
require 'active_support'
require 'active_support/core_ext'
require 'shoulda'
require 'mocha/setup'
require 'mocha/api'
require 'bourne'
require 'shoulda/context'
require 'mime/types'
require 'pathname'
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__), '..')))
$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', 'paperclip')
require File.join(ROOT, 'lib', 'paperclip.rb')
require './shoulda_macros/paperclip'
FIXTURES_DIR = File.join(File.dirname(__FILE__), "fixtures")
config = YAML::load(IO.read(File.dirname(__FILE__) + '/database.yml'))
ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + "/debug.log")
ActiveRecord::Base.establish_connection(config['test'])
Paperclip.options[:logger] = ActiveRecord::Base.logger
def using_protected_attributes?
ActiveRecord::VERSION::MAJOR < 4
end
Dir[File.join(ROOT, 'spec', 'support', '**', '*.rb')].each{|f| require f }
Rails = FakeRails.new('test', Pathname.new(ROOT).join('tmp'))
ActiveSupport::Deprecation.silenced = true
def require_everything_in_directory(directory_name)
Dir[File.join(File.dirname(__FILE__), directory_name, '*')].each do |f|
require f
RSpec.configure do |config|
config.include Assertions
config.mock_framework = :mocha
config.before(:all) do
rebuild_model
end
end
require_everything_in_directory('support')
def using_protected_attributes?
ActiveRecord::VERSION::MAJOR < 4
end
def reset_class class_name
ActiveRecord::Base.send(:include, Paperclip::Glue)
......@@ -171,22 +122,22 @@ ensure
end
def should_accept_dummy_class
should "accept the class" do
assert_accepts @matcher, Dummy
it "accepts the class" do
expect(@matcher).to accept(Dummy)
end
should "accept an instance of that class" do
assert_accepts @matcher, Dummy.new
it "accepts an instance of that class" do
expect(@matcher).to accept(Dummy.new)
end
end
def should_reject_dummy_class
should "reject the class" do
assert_rejects @matcher, Dummy
it "rejects the class" do
expect(@matcher).to_not accept(Dummy)
end
should "reject an instance of that class" do
assert_rejects @matcher, Dummy.new
it "rejects an instance of that class" do
expect(@matcher).to_not accept(Dummy.new)
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