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' })
......
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 '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
......
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'
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 '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
......
# 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
......
# 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 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