Module Shoulda::ActiveRecord::Macros
In: lib/shoulda/active_record/macros.rb

Macro test helpers for your active record models

These helpers will test most of the validations and associations for your ActiveRecord models.

  class UserTest < Test::Unit::TestCase
    should_validate_presence_of :name, :phone_number
    should_not_allow_values_for :phone_number, "abcd", "1234"
    should_allow_values_for :phone_number, "(123) 456-7890"

    should_not_allow_mass_assignment_of :password

    should_have_one :profile
    should_have_many :dogs
    should_have_many :messes, :through => :dogs
    should_belong_to :lover
  end

For all of these helpers, the last parameter may be a hash of options.

Methods

Included Modules

Helpers Matchers

Public Instance methods

Ensures that the attribute can be set on mass update.

  should_allow_mass_assignment_of :first_name, :last_name

[Source]

     # File lib/shoulda/active_record/macros.rb, line 104
104:       def should_allow_mass_assignment_of(*attributes)
105:         get_options!(attributes)
106:         klass = model_class
107: 
108:         attributes.each do |attribute|
109:           matcher = allow_mass_assignment_of(attribute)
110:           should matcher.description do
111:             assert_accepts matcher, klass.new
112:           end
113:         end
114:       end

Ensures that the attribute can be set to the given values.

If an instance variable has been created in the setup named after the model being tested, then this method will use that. Otherwise, it will create a new instance to test against.

Example:

  should_allow_values_for :isbn, "isbn 1 2345 6789 0", "ISBN 1-2345-6789-0"

[Source]

     # File lib/shoulda/active_record/macros.rb, line 188
188:       def should_allow_values_for(attribute, *good_values)
189:         get_options!(good_values)
190:         klass = model_class
191:         good_values.each do |value|
192:           matcher = allow_value(value).for(attribute)
193:           should matcher.description do
194:             assert_accepts matcher, get_instance_of(klass)
195:           end
196:         end
197:       end

Ensure that the belongs_to relationship exists.

  should_belong_to :parent

[Source]

     # File lib/shoulda/active_record/macros.rb, line 411
411:       def should_belong_to(*associations)
412:         dependent = get_options!(associations, :dependent)
413:         klass = model_class
414:         associations.each do |association|
415:           matcher = belong_to(association).dependent(dependent)
416:           should matcher.description do
417:             assert_accepts(matcher, klass.new)
418:           end
419:         end
420:       end

Ensures that the length of the attribute is at least a certain length

If an instance variable has been created in the setup named after the model being tested, then this method will use that. Otherwise, it will create a new instance to test against.

Options:

  • :short_message - value the test expects to find in errors.on(:attribute). Regexp or string. Default = I18n.translate(‘activerecord.errors.messages.too_short’) % min_length

Example:

  should_ensure_length_at_least :name, 3

[Source]

     # File lib/shoulda/active_record/macros.rb, line 244
244:       def should_ensure_length_at_least(attribute, min_length, opts = {})
245:         short_message = get_options!([opts], :short_message)
246:         klass = model_class
247: 
248:         matcher = ensure_length_of(attribute).
249:           is_at_least(min_length).
250:           with_short_message(short_message)
251: 
252:         should matcher.description do
253:           assert_accepts matcher, get_instance_of(klass)
254:         end
255:       end

Ensures that the length of the attribute is in the given range

If an instance variable has been created in the setup named after the model being tested, then this method will use that. Otherwise, it will create a new instance to test against.

Options:

  • :short_message - value the test expects to find in errors.on(:attribute). Regexp or string. Default = I18n.translate(‘activerecord.errors.messages.too_short’) % range.first
  • :long_message - value the test expects to find in errors.on(:attribute). Regexp or string. Default = I18n.translate(‘activerecord.errors.messages.too_long’) % range.last

Example:

  should_ensure_length_in_range :password, (6..20)

[Source]

     # File lib/shoulda/active_record/macros.rb, line 214
214:       def should_ensure_length_in_range(attribute, range, opts = {})
215:         short_message, long_message = get_options!([opts], 
216:                                                    :short_message,
217:                                                    :long_message)
218:         klass = model_class
219: 
220:         matcher = ensure_length_of(attribute).
221:           is_at_least(range.first).
222:           with_short_message(short_message).
223:           is_at_most(range.last).
224:           with_long_message(long_message)
225: 
226:         should matcher.description do
227:           assert_accepts matcher, get_instance_of(klass)
228:         end
229:       end

Ensures that the length of the attribute is exactly a certain length

If an instance variable has been created in the setup named after the model being tested, then this method will use that. Otherwise, it will create a new instance to test against.

Options:

  • :message - value the test expects to find in errors.on(:attribute). Regexp or string. Default = I18n.translate(‘activerecord.errors.messages.wrong_length’) % length

Example:

  should_ensure_length_is :ssn, 9

[Source]

     # File lib/shoulda/active_record/macros.rb, line 270
270:       def should_ensure_length_is(attribute, length, opts = {})
271:         message = get_options!([opts], :message)
272:         klass   = model_class
273:         matcher = ensure_length_of(attribute).
274:           is_equal_to(length).
275:           with_message(message)
276: 
277:         should matcher.description do
278:           assert_accepts matcher, get_instance_of(klass)
279:         end
280:       end

Ensure that the attribute is in the range specified

If an instance variable has been created in the setup named after the model being tested, then this method will use that. Otherwise, it will create a new instance to test against.

Options:

  • :low_message - value the test expects to find in errors.on(:attribute). Regexp or string. Default = I18n.translate(‘activerecord.errors.messages.inclusion’)
  • :high_message - value the test expects to find in errors.on(:attribute). Regexp or string. Default = I18n.translate(‘activerecord.errors.messages.inclusion’)

Example:

  should_ensure_value_in_range :age, (0..100)

[Source]

     # File lib/shoulda/active_record/macros.rb, line 297
297:       def should_ensure_value_in_range(attribute, range, opts = {})
298:         message, low_message, high_message = get_options!([opts],
299:                                                           :message,
300:                                                           :low_message,
301:                                                           :high_message)
302:         klass = model_class
303:         matcher = ensure_inclusion_of(attribute).
304:           in_range(range).
305:           with_message(message).
306:           with_low_message(low_message).
307:           with_high_message(high_message)
308:         should matcher.description do
309:           assert_accepts matcher, get_instance_of(klass)
310:         end
311:       end

Ensures that the has_and_belongs_to_many relationship exists, and that the join table is in place.

  should_have_and_belong_to_many :posts, :cars

[Source]

     # File lib/shoulda/active_record/macros.rb, line 395
395:       def should_have_and_belong_to_many(*associations)
396:         get_options!(associations)
397:         klass = model_class
398: 
399:         associations.each do |association|
400:           matcher = have_and_belong_to_many(association)
401:           should matcher.description do
402:             assert_accepts(matcher, klass.new)
403:           end
404:         end
405:       end

Ensure that the given class methods are defined on the model.

  should_have_class_methods :find, :destroy

[Source]

     # File lib/shoulda/active_record/macros.rb, line 426
426:       def should_have_class_methods(*methods)
427:         get_options!(methods)
428:         klass = model_class
429:         methods.each do |method|
430:           should "respond to class method ##{method}" do
431:             assert_respond_to klass, method, "#{klass.name} does not have class method #{method}"
432:           end
433:         end
434:       end
should_have_db_column(*columns)

Ensure that the given columns are defined on the models backing SQL table. Also aliased to should_have_index for readability. Takes the same options available in migrations: :type, :precision, :limit, :default, :null, and :scale

Examples:

  should_have_db_columns :id, :email, :name, :created_at

  should_have_db_column :email,  :type => "string", :limit => 255
  should_have_db_column :salary, :decimal, :precision => 15, :scale => 2
  should_have_db_column :admin,  :default => false, :null => false

[Source]

     # File lib/shoulda/active_record/macros.rb, line 463
463:       def should_have_db_columns(*columns)
464:         column_type, precision, limit, default, null, scale, sql_type = 
465:           get_options!(columns, :type, :precision, :limit,
466:                                 :default, :null, :scale, :sql_type)
467:         klass = model_class
468:         columns.each do |name|
469:           matcher = have_db_column(name).
470:                       of_type(column_type).
471:                       with_options(:precision => precision, :limit    => limit,
472:                                    :default   => default,   :null     => null,
473:                                    :scale     => scale,     :sql_type => sql_type)
474:           should matcher.description do
475:             assert_accepts(matcher, klass.new)
476:           end
477:         end
478:       end
should_have_index(*columns)

Ensures that there are DB indices on the given columns or tuples of columns. Also aliased to should_have_index for readability

Options:

  • :unique - whether or not the index has a unique constraint. Use true to explicitly test for a unique constraint. Use false to explicitly test for a non-unique constraint. Use nil if you don‘t care whether the index is unique or not. Default = nil

Examples:

  should_have_indices :email, :name, [:commentable_type, :commentable_id]
  should_have_index :age
  should_have_index :ssn, :unique => true

[Source]

     # File lib/shoulda/active_record/macros.rb, line 498
498:       def should_have_indices(*columns)
499:         unique = get_options!(columns, :unique)
500:         klass  = model_class
501:         
502:         columns.each do |column|
503:           matcher = have_index(column).unique(unique)
504:           should matcher.description do
505:             assert_accepts(matcher, klass.new)
506:           end
507:         end
508:       end

Ensure that the given instance methods are defined on the model.

  should_have_instance_methods :email, :name, :name=

[Source]

     # File lib/shoulda/active_record/macros.rb, line 440
440:       def should_have_instance_methods(*methods)
441:         get_options!(methods)
442:         klass = model_class
443:         methods.each do |method|
444:           should "respond to instance method ##{method}" do
445:             assert_respond_to klass.new, method, "#{klass.name} does not have instance method #{method}"
446:           end
447:         end
448:       end

Ensures that the has_many relationship exists. Will also test that the associated table has the required columns. Works with polymorphic associations.

Options:

  • :through - association name for has_many :through
  • :dependent - tests that the association makes use of the dependent option.

Example:

  should_have_many :friends
  should_have_many :enemies, :through => :friends
  should_have_many :enemies, :dependent => :destroy

[Source]

     # File lib/shoulda/active_record/macros.rb, line 358
358:       def should_have_many(*associations)
359:         through, dependent = get_options!(associations, :through, :dependent)
360:         klass = model_class
361:         associations.each do |association|
362:           matcher = have_many(association).through(through).dependent(dependent)
363:           should matcher.description do
364:             assert_accepts(matcher, klass.new)
365:           end
366:         end
367:       end

Ensures that the model has a method named scope_name that returns a NamedScope object with the proxy options set to the options you supply. scope_name can be either a symbol, or a method call which will be evaled against the model. The eval‘d method call has access to all the same instance variables that a should statement would.

Options: Any of the options that the named scope would pass on to find.

Example:

  should_have_named_scope :visible, :conditions => {:visible => true}

Passes for

  named_scope :visible, :conditions => {:visible => true}

Or for

  def self.visible
    scoped(:conditions => {:visible => true})
  end

You can test lambdas or methods that return ActiveRecord#scoped calls:

  should_have_named_scope 'recent(5)', :limit => 5
  should_have_named_scope 'recent(1)', :limit => 1

Passes for

  named_scope :recent, lambda {|c| {:limit => c}}

Or for

  def self.recent(c)
    scoped(:limit => c)
  end

[Source]

     # File lib/shoulda/active_record/macros.rb, line 579
579:       def should_have_named_scope(scope_call, find_options = nil)
580:         klass = model_class
581:         matcher = have_named_scope(scope_call).finding(find_options)
582:         should matcher.description do
583:           assert_accepts matcher.in_context(self), klass.new
584:         end
585:       end

Ensure that the has_one relationship exists. Will also test that the associated table has the required columns. Works with polymorphic associations.

Options:

  • :dependent - tests that the association makes use of the dependent option.

Example:

  should_have_one :god # unless hindu

[Source]

     # File lib/shoulda/active_record/macros.rb, line 379
379:       def should_have_one(*associations)
380:         dependent = get_options!(associations, :dependent)
381:         klass = model_class
382:         associations.each do |association|
383:           matcher = have_one(association).dependent(dependent)
384:           should matcher.description do
385:             assert_accepts(matcher, klass.new)
386:           end
387:         end
388:       end

Ensures that the attribute cannot be changed once the record has been created.

  should_have_readonly_attributes :password, :admin_flag

[Source]

     # File lib/shoulda/active_record/macros.rb, line 143
143:       def should_have_readonly_attributes(*attributes)
144:         get_options!(attributes)
145:         klass = model_class
146: 
147:         attributes.each do |attribute|
148:           matcher = have_readonly_attribute(attribute)
149:           should matcher.description do
150:             assert_accepts matcher, klass.new
151:           end
152:         end
153:       end

Ensures that the attribute cannot be set on mass update.

  should_not_allow_mass_assignment_of :password, :admin_flag

[Source]

     # File lib/shoulda/active_record/macros.rb, line 120
120:       def should_not_allow_mass_assignment_of(*attributes)
121:         get_options!(attributes)
122:         klass = model_class
123: 
124:         attributes.each do |attribute|
125:           matcher = allow_mass_assignment_of(attribute)
126:           should "not #{matcher.description}" do
127:             assert_rejects matcher, klass.new
128:           end
129:         end
130:       end

Ensures that the attribute cannot be set to the given values

If an instance variable has been created in the setup named after the model being tested, then this method will use that. Otherwise, it will create a new instance to test against.

Options:

  • :message - value the test expects to find in errors.on(:attribute). Regexp or string. Default = I18n.translate(‘activerecord.errors.messages.invalid’)

Example:

  should_not_allow_values_for :isbn, "bad 1", "bad 2"

[Source]

     # File lib/shoulda/active_record/macros.rb, line 168
168:       def should_not_allow_values_for(attribute, *bad_values)
169:         message = get_options!(bad_values, :message)
170:         klass = model_class
171:         bad_values.each do |value|
172:           matcher = allow_value(value).for(attribute).with_message(message)
173:           should "not #{matcher.description}" do
174:             assert_rejects matcher, get_instance_of(klass)
175:           end
176:         end
177:       end

Deprecated. See should_validate_numericality_of

[Source]

     # File lib/shoulda/active_record/macros.rb, line 339
339:       def should_only_allow_numeric_values_for(*attributes)
340:         warn "[DEPRECATION] should_only_allow_numeric_values_for is " <<
341:              "deprecated. Use should_validate_numericality_of instead."
342:         should_validate_numericality_of(*attributes)
343:       end

Deprecated. See should_not_allow_mass_assignment_of

[Source]

     # File lib/shoulda/active_record/macros.rb, line 133
133:       def should_protect_attributes(*attributes)
134:         warn "[DEPRECATION] should_protect_attributes is deprecated. " <<
135:              "Use should_not_allow_mass_assignment_of instead."
136:         should_not_allow_mass_assignment_of(*attributes)
137:       end

Deprecated. See should_validate_uniqueness_of

[Source]

     # File lib/shoulda/active_record/macros.rb, line 538
538:       def should_require_acceptance_of(*attributes)
539:         warn "[DEPRECATION] should_require_acceptance_of is deprecated. " <<
540:              "Use should_validate_acceptance_of instead."
541:         should_validate_acceptance_of(*attributes)
542:       end

Deprecated. See should_validate_presence_of

[Source]

    # File lib/shoulda/active_record/macros.rb, line 52
52:       def should_require_attributes(*attributes)
53:         warn "[DEPRECATION] should_require_attributes is deprecated. " <<
54:              "Use should_validate_presence_of instead."
55:         should_validate_presence_of(*attributes)
56:       end

Deprecated. See should_validate_uniqueness_of

[Source]

    # File lib/shoulda/active_record/macros.rb, line 94
94:       def should_require_unique_attributes(*attributes)
95:         warn "[DEPRECATION] should_require_unique_attributes is deprecated. " <<
96:              "Use should_validate_uniqueness_of instead."
97:         should_validate_uniqueness_of(*attributes)
98:       end

Ensures that the model cannot be saved if one of the attributes listed is not accepted.

If an instance variable has been created in the setup named after the model being tested, then this method will use that. Otherwise, it will create a new instance to test against.

Options:

  • :message - value the test expects to find in errors.on(:attribute). Regexp or string. Default = I18n.translate(‘activerecord.errors.messages.accepted’)

Example:

  should_validate_acceptance_of :eula

[Source]

     # File lib/shoulda/active_record/macros.rb, line 525
525:       def should_validate_acceptance_of(*attributes)
526:         message = get_options!(attributes, :message)
527:         klass = model_class
528: 
529:         attributes.each do |attribute|
530:           matcher = validate_acceptance_of(attribute).with_message(message)
531:           should matcher.description do
532:             assert_accepts matcher, get_instance_of(klass)
533:           end
534:         end
535:       end

Ensure that the attribute is numeric

If an instance variable has been created in the setup named after the model being tested, then this method will use that. Otherwise, it will create a new instance to test against.

Options:

  • :message - value the test expects to find in errors.on(:attribute). Regexp or string. Default = I18n.translate(‘activerecord.errors.messages.not_a_number’)

Example:

  should_validate_numericality_of :age

[Source]

     # File lib/shoulda/active_record/macros.rb, line 326
326:       def should_validate_numericality_of(*attributes)
327:         message = get_options!(attributes, :message)
328:         klass = model_class
329:         attributes.each do |attribute|
330:           matcher = validate_numericality_of(attribute).
331:             with_message(message)
332:           should matcher.description do
333:             assert_accepts matcher, get_instance_of(klass)
334:           end
335:         end
336:       end

Ensures that the model cannot be saved if one of the attributes listed is not present.

If an instance variable has been created in the setup named after the model being tested, then this method will use that. Otherwise, it will create a new instance to test against.

Options:

  • :message - value the test expects to find in errors.on(:attribute). Regexp or string. Default = I18n.translate(‘activerecord.errors.messages.blank’)

Example:

  should_validate_presence_of :name, :phone_number

[Source]

    # File lib/shoulda/active_record/macros.rb, line 39
39:       def should_validate_presence_of(*attributes)
40:         message = get_options!(attributes, :message)
41:         klass = model_class
42: 
43:         attributes.each do |attribute|
44:           matcher = validate_presence_of(attribute).with_message(message)
45:           should matcher.description do
46:             assert_accepts(matcher, get_instance_of(klass))
47:           end
48:         end
49:       end
  • :message - value the test expects to find in errors.on(:attribute). Regexp or string. Default = I18n.translate(‘activerecord.errors.messages.taken’)
  • :scoped_to - field(s) to scope the uniqueness to.
  • :case_sensitive - whether or not uniqueness is defined by an exact match. Ignored by non-text attributes. Default = true

Examples:

  should_validate_uniqueness_of :keyword, :username
  should_validate_uniqueness_of :name, :message => "O NOES! SOMEONE STOELED YER NAME!"
  should_validate_uniqueness_of :email, :scoped_to => :name
  should_validate_uniqueness_of :address, :scoped_to => [:first_name, :last_name]
  should_validate_uniqueness_of :email, :case_sensitive => false

[Source]

    # File lib/shoulda/active_record/macros.rb, line 76
76:       def should_validate_uniqueness_of(*attributes)
77:         message, scope, case_sensitive = get_options!(attributes, :message, :scoped_to, :case_sensitive)
78:         scope = [*scope].compact
79:         case_sensitive = true if case_sensitive.nil?
80: 
81:         klass = model_class
82: 
83:         attributes.each do |attribute|
84:           matcher = validate_uniqueness_of(attribute).
85:             with_message(message).scoped_to(scope)
86:           matcher = matcher.case_insensitive unless case_sensitive
87:           should matcher.description do
88:             assert_accepts(matcher, get_instance_of(klass))
89:           end
90:         end
91:       end

[Validate]