Skip to content

Instantly share code, notes, and snippets.

@RobertDober
Forked from mallain/test_helper.rb
Created May 12, 2010 16:59
Show Gist options
  • Save RobertDober/398828 to your computer and use it in GitHub Desktop.
Save RobertDober/398828 to your computer and use it in GitHub Desktop.
# C'est très bien, j'ai apporté une simple somplification, inutile d'invoquer #save quand
# l'introspection API te donne #valid?. N'oublions jamais, nous testons nos applications, et *pas* *Rails*.
#
# Par contre Shoulda fait déjà tout ça pour toi, je te montre comment ci-dessous.
# Generate generic tests for instance and unsaved objects
# object as String
# uniqueness_attr as Array
# model_generic_tests("account", %w(name))
def model_generic_tests(object, uniqueness_attr=[])
context "A #{object} instance" do
setup do
@object = Factory(object.to_sym)
end
should "return its name" do
assert @object.name
end
uniqueness_attr.each do |attr|
model_uniqueness_tests(@object, attr)
end
should "not save #{object} without name" do
@object.name = nil
### assert !@object.save
assert !@object.valid?
end
end
context "A unsaved #{object} instance" do
setup do
@object = Factory.build(object.to_sym, :name => nil)
end
should "not save #{object} without name" do
### assert !@object.save
assert !@object.valid?
end
end
end
# Generate uniqueness_tests
# object as String
# attribute as String
# model_uniqueness_tests("account", "name")
def model_uniqueness_tests(object, attribute)
should "have unique #{attribute}" do
object = Factory(object.to_sym, attribute.to_sym => "unique")
object_not_unique = Factory.build(object.to_sym, attribute.to_sym => "unique")
### assert !object_not_unique.save
assert !object_not_unique.valid? # il est triste que Shoulda n'implèmente pas assert_invalid :(
end
end
############
###
### Tout ça est déjà implementé par Shoulda :(
###
############
include 'test_helper'
class MyModelTest < ActiveSupport::UnitTest
should_validate_uniqueness_of :name
should_validate_presence_of :name
### http://rdoc.info/rdoc/thoughtbot/shoulda/blob/272aad1c4d5897ff232ec9a75a73c85b0f64554a/Shoulda/ActiveRecord/Macros.html#should_validate_uniqueness_of-instance_method
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment