rmm5t / shoulda forked from thoughtbot/shoulda

Makes tests easy on the fingers and the eyes

This URL has Read+Write access

shoulda / lib / shoulda / active_record_helpers.rb
100644 558 lines (504 sloc) 23.111 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
module ThoughtBot # :nodoc:
  module Shoulda # :nodoc:
    # = 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_require_attributes :name, :phone_number
    # should_not_allow_values_for :phone_number, "abcd", "1234"
    # should_allow_values_for :phone_number, "(123) 456-7890"
    #
    # should_protect_attributes :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.
    #
    module ActiveRecord
      # Ensures that the model cannot be saved if one of the attributes listed is not present.
      #
      # Options:
      # * <tt>:message</tt> - value the test expects to find in <tt>errors.on(:attribute)</tt>.
      # Regexp or string. Default = <tt>/blank/</tt>
      #
      # Example:
      # should_require_attributes :name, :phone_number
      #
      def should_require_attributes(*attributes)
        message = get_options!(attributes, :message)
        message ||= /blank/
        attributes.each do |attribute|
          should_not_allow_values_for attribute, nil, :message => message, :should => "require #{attribute} to be set"
        end
      end
 
      # Ensures that the model cannot be saved if one of the attributes listed is not unique.
      # Requires an existing record
      #
      # Options:
      # * <tt>:message</tt> - value the test expects to find in <tt>errors.on(:attribute)</tt>.
      # Regexp or string. Default = <tt>/taken/</tt>
      # * <tt>:scoped_to</tt> - field(s) to scope the uniqueness to.
      #
      # Examples:
      # should_require_unique_attributes :keyword, :username
      # should_require_unique_attributes :name, :message => "O NOES! SOMEONE STOELED YER NAME!"
      # should_require_unique_attributes :email, :scoped_to => :name
      # should_require_unique_attributes :address, :scoped_to => [:first_name, :last_name]
      #
      def should_require_unique_attributes(*attributes)
        message, scope = get_options!(attributes, :message, :scoped_to)
        scope = [*scope].compact
        message ||= /taken/
 
        klass = model_class
        attributes.each do |attribute|
          attribute = attribute.to_sym
          should "require unique value for #{attribute}#{" scoped to #{scope.join(', ')}" unless scope.blank?}" do
            assert existing = klass.find(:first), "Can't find first #{klass}"
            object = klass.new
            existing_value = existing.send(attribute)
 
            if !scope.blank?
              scope.each do |s|
                assert_respond_to object, :"#{s}=", "#{klass.name} doesn't seem to have a #{s} attribute."
                object.send("#{s}=", existing.send(s))
              end
            end
            assert_bad_value(object, attribute, existing_value, message)
 
            # Now test that the object is valid when changing the scoped attribute
            # TODO: There is a chance that we could change the scoped field
            # to a value that's already taken. An alternative implementation
            # could actually find all values for scope and create a unique
            # one.
            if !scope.blank?
              scope.each do |s|
                # Assume the scope is a foreign key if the field is nil
                object.send("#{s}=", existing.send(s).nil? ? 1 : existing.send(s).next)
                assert_good_value(object, attribute, existing_value, message)
              end
            end
          end
        end
      end
 
      # Ensures that the attribute cannot be set on mass update.
      # Requires an existing record.
      #
      # should_protect_attributes :password, :admin_flag
      #
      def should_protect_attributes(*attributes)
        get_options!(attributes)
        klass = model_class
 
        attributes.each do |attribute|
          attribute = attribute.to_sym
          should "protect #{attribute} from mass updates" do
            protected = klass.protected_attributes || []
            accessible = klass.accessible_attributes || []
 
            assert protected.include?(attribute.to_s) || !accessible.include?(attribute.to_s),
                   (accessible.empty? ?
                     "#{klass} is protecting #{protected.to_a.to_sentence}, but not #{attribute}." :
                     "#{klass} has made #{attribute} accessible")
          end
        end
      end
 
      # Ensures that the attribute cannot be changed once the record has been created.
      # Requires an existing record.
      #
      # should_have_readonly_attributes :password, :admin_flag
      #
      def should_have_readonly_attributes(*attributes)
        get_options!(attributes)
        klass = model_class
 
        attributes.each do |attribute|
          attribute = attribute.to_sym
          should "make #{attribute} read-only" do
            readonly = klass.readonly_attributes || []
 
            assert readonly.include?(attribute.to_s),
                   (readonly.empty? ?
                     "#{klass} attribute #{attribute} is not read-only" :
                     "#{klass} is making #{readonly.to_a.to_sentence} read-only, but not #{attribute}.")
          end
        end
      end
 
      # Ensures that the attribute cannot be set to the given values
      # Requires an existing record
      #
      # Options:
      # * <tt>:message</tt> - value the test expects to find in <tt>errors.on(:attribute)</tt>.
      # Regexp or string. Default = <tt>/invalid/</tt>
      # * <tt>:should</tt> - an override of the default should test name.
      # Usually only used by other macros.
      #
      # Example:
      # should_not_allow_values_for :isbn, "bad 1", "bad 2"
      #
      def should_not_allow_values_for(attribute, *bad_values)
        message, name = get_options!(bad_values, :message, :should)
        message ||= /invalid/
        klass = model_class
        bad_values.each do |v|
          name ||= "not allow #{attribute} to be set to #{v.inspect}"
          should name do
            object = klass.new
            assert_bad_value(object, attribute, v, message)
          end
        end
      end
 
      # Ensures that the attribute can be set to the given values.
      # Requires an existing record
      #
      # Options:
      # * <tt>:message</tt> - value the test shouldn't find in <tt>errors.on(:attribute)</tt>.
      # Regexp or string. Default = <tt>//</tt>
      # * <tt>:should</tt> - an override of the default should test name.
      # Usually only used by other macros.
      #
      # Example:
      # should_allow_values_for :isbn, "isbn 1 2345 6789 0", "ISBN 1-2345-6789-0"
      #
      def should_allow_values_for(attribute, *good_values)
        message, name = get_options!(good_values, :message, :should)
        message ||= //
        klass = model_class
        good_values.each do |v|
          name ||= "allow #{attribute} to be set to #{v.inspect}"
          should name do
            object = klass.new
            assert_good_value(object, attribute, v, message)
          end
        end
      end
 
      # Ensures that the length of the attribute is in the given range
      # Requires an existing record
      #
      # Options:
      # * <tt>:short_message</tt> - value the test expects to find in <tt>errors.on(:attribute)</tt>.
      # Regexp or string. Default = <tt>/short/</tt>
      # * <tt>:long_message</tt> - value the test expects to find in <tt>errors.on(:attribute)</tt>.
      # Regexp or string. Default = <tt>/long/</tt>
      #
      # Example:
      # should_ensure_length_in_range :password, (6..20)
      #
      def should_ensure_length_in_range(attribute, range, opts = {})
        short_message, long_message = get_options!([opts], :short_message, :long_message)
        short_message ||= /short/
        long_message ||= /long/
 
        min_length = range.first
        max_length = range.last
        same_length = (min_length == max_length)
 
        if min_length > 0
          min_value = "x" * (min_length - 1)
          should_not_allow_values_for attribute, min_value, :message => short_message, :should => "not allow #{attribute} to be less than #{min_length} chars long"
        end
 
        if min_length > 0
          min_value = "x" * min_length
          should_allow_values_for attribute, min_value, :message => short_message, :should => "allow #{attribute} to be exactly #{min_length} chars long"
        end
 
        max_value = "x" * (max_length + 1)
        should_not_allow_values_for attribute, max_value, :message => long_message, :should => "not allow #{attribute} to be more than #{max_length} chars long"
 
        unless same_length
          max_value = "x" * max_length
          should_allow_values_for attribute, max_value, :message => long_message, :should => "allow #{attribute} to be exactly #{max_length} chars long"
        end
      end
 
      # Ensures that the length of the attribute is at least a certain length
      # Requires an existing record
      #
      # Options:
      # * <tt>:short_message</tt> - value the test expects to find in <tt>errors.on(:attribute)</tt>.
      # Regexp or string. Default = <tt>/short/</tt>
      #
      # Example:
      # should_ensure_length_at_least :name, 3
      #
      def should_ensure_length_at_least(attribute, min_length, opts = {})
        short_message = get_options!([opts], :short_message)
        short_message ||= /short/
 
        if min_length > 0
          min_value = "x" * (min_length - 1)
          should_not_allow_values_for attribute, min_value, :message => short_message, :should => "not allow #{attribute} to be less than #{min_length} chars long"
        end
 
        valid_value = "x" * (min_length)
        should_allow_values_for attribute, valid_value, :message => short_message, :should => "allow #{attribute} to be at least #{min_length} chars long"
      end
 
      # Ensures that the length of the attribute is exactly a certain length
      # Requires an existing record
      #
      # Options:
      # * <tt>:message</tt> - value the test expects to find in <tt>errors.on(:attribute)</tt>.
      # Regexp or string. Default = <tt>/short/</tt>
      #
      # Example:
      # should_ensure_length_is :ssn, 9
      #
      def should_ensure_length_is(attribute, length, opts = {})
        message = get_options!([opts], :message)
        message ||= /wrong length/
 
        min_value = "x" * (length - 1)
        should_not_allow_values_for attribute, min_value, :message => message, :should => "not allow #{attribute} to be less than #{length} chars long"
 
        max_value = "x" * (length + 1)
        should_not_allow_values_for attribute, max_value, :message => message, :should => "not allow #{attribute} to be greater than #{length} chars long"
 
        valid_value = "x" * (length)
        should_allow_values_for attribute, valid_value, :message => message, :should => "allow #{attribute} to be #{length} chars long"
      end
 
      # Ensure that the attribute is in the range specified
      # Requires an existing record
      #
      # Options:
      # * <tt>:low_message</tt> - value the test expects to find in <tt>errors.on(:attribute)</tt>.
      # Regexp or string. Default = <tt>/included/</tt>
      # * <tt>:high_message</tt> - value the test expects to find in <tt>errors.on(:attribute)</tt>.
      # Regexp or string. Default = <tt>/included/</tt>
      #
      # Example:
      # should_ensure_value_in_range :age, (0..100)
      #
      def should_ensure_value_in_range(attribute, range, opts = {})
        low_message, high_message = get_options!([opts], :low_message, :high_message)
        low_message ||= /included/
        high_message ||= /included/
 
        min = range.first
        max = range.last
 
        should_not_allow_values_for attribute, (min - 1), :message => low_message, :should => "not allow #{attribute} to be less than #{min}"
        should_allow_values_for attribute, min, :message => low_message, :should => "allow #{attribute} to be #{min}"
        should_not_allow_values_for attribute, (max + 1), :message => high_message, :should => "not allow #{attribute} to be more than #{max}"
        should_allow_values_for attribute, max, :message => high_message, :should => "allow #{attribute} to be #{max}"
      end
 
      # Ensure that the attribute is numeric
      # Requires an existing record
      #
      # Options:
      # * <tt>:message</tt> - value the test expects to find in <tt>errors.on(:attribute)</tt>.
      # Regexp or string. Default = <tt>/number/</tt>
      #
      # Example:
      # should_only_allow_numeric_values_for :age
      #
      def should_only_allow_numeric_values_for(*attributes)
        message = get_options!(attributes, :message)
        message ||= /number/
        attributes.each do |attribute|
          should_not_allow_values_for attribute, "abcd", :message => message, :should => "only allow numeric values for #{attribute}"
        end
      end
 
      # Ensures that the has_many relationship exists. Will also test that the
      # associated table has the required columns. Works with polymorphic
      # associations.
      #
      # Options:
      # * <tt>:through</tt> - association name for <tt>has_many :through</tt>
      # * <tt>:dependent</tt> - 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
      #
      def should_have_many(*associations)
        through, dependent = get_options!(associations, :through, :dependent)
        klass = model_class
        associations.each do |association|
          name = "have many #{association}"
          name += " through #{through}" if through
          name += " dependent => #{dependent}" if dependent
          should name do
            reflection = klass.reflect_on_association(association)
            assert reflection, "#{klass.name} does not have any relationship to #{association}"
            assert_equal :has_many, reflection.macro
 
            associated_klass = (reflection.options[:class_name] || association.to_s.classify).constantize
 
            if through
              through_reflection = klass.reflect_on_association(through)
              assert through_reflection, "#{klass.name} does not have any relationship to #{through}"
              assert_equal(through, reflection.options[:through])
            end
 
            if dependent
              assert_equal dependent.to_s,
                           reflection.options[:dependent].to_s,
                           "#{associated_klass.name} should have #{dependent} dependency"
            end
 
            # Check for the existence of the foreign key on the other table
            unless reflection.options[:through]
              if reflection.options[:foreign_key]
                fk = reflection.options[:foreign_key]
              elsif reflection.options[:as]
                fk = reflection.options[:as].to_s.foreign_key
              else
                fk = reflection.primary_key_name
              end
 
              assert associated_klass.column_names.include?(fk.to_s),
                     "#{associated_klass.name} does not have a #{fk} foreign key."
            end
          end
        end
      end
 
      # Ensure that the has_one relationship exists. Will also test that the
      # associated table has the required columns. Works with polymorphic
      # associations.
      #
      # Example:
      # should_have_one :god # unless hindu
      #
      def should_have_one(*associations)
        get_options!(associations)
        klass = model_class
        associations.each do |association|
          should "have one #{association}" do
            reflection = klass.reflect_on_association(association)
            assert reflection, "#{klass.name} does not have any relationship to #{association}"
            assert_equal :has_one, reflection.macro
 
            associated_klass = (reflection.options[:class_name] || association.to_s.camelize).constantize
 
            if reflection.options[:foreign_key]
              fk = reflection.options[:foreign_key]
            elsif reflection.options[:as]
              fk = reflection.options[:as].to_s.foreign_key
              fk_type = fk.gsub(/_id$/, '_type')
              assert associated_klass.column_names.include?(fk_type),
                     "#{associated_klass.name} does not have a #{fk_type} column."
            else
              fk = klass.name.foreign_key
            end
            assert associated_klass.column_names.include?(fk.to_s),
                   "#{associated_klass.name} does not have a #{fk} foreign key."
          end
        end
      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
      #
      def should_have_and_belong_to_many(*associations)
        get_options!(associations)
        klass = model_class
 
        associations.each do |association|
          should "should have and belong to many #{association}" do
            reflection = klass.reflect_on_association(association)
            assert reflection, "#{klass.name} does not have any relationship to #{association}"
            assert_equal :has_and_belongs_to_many, reflection.macro
            table = reflection.options[:join_table]
            assert ::ActiveRecord::Base.connection.tables.include?(table), "table #{table} doesn't exist"
          end
        end
      end
 
      # Ensure that the belongs_to relationship exists.
      #
      # should_belong_to :parent
      #
      def should_belong_to(*associations)
        get_options!(associations)
        klass = model_class
        associations.each do |association|
          should "belong_to #{association}" do
            reflection = klass.reflect_on_association(association)
            assert reflection, "#{klass.name} does not have any relationship to #{association}"
            assert_equal :belongs_to, reflection.macro
 
            unless reflection.options[:polymorphic]
              associated_klass = (reflection.options[:class_name] || association.to_s.classify).constantize
              fk = reflection.options[:foreign_key] || reflection.primary_key_name
              assert klass.column_names.include?(fk.to_s), "#{klass.name} does not have a #{fk} foreign key."
            end
          end
        end
      end
 
      # Ensure that the given class methods are defined on the model.
      #
      # should_have_class_methods :find, :destroy
      #
      def should_have_class_methods(*methods)
        get_options!(methods)
        klass = model_class
        methods.each do |method|
          should "respond to class method ##{method}" do
            assert_respond_to klass, method, "#{klass.name} does not have class method #{method}"
          end
        end
      end
 
      # Ensure that the given instance methods are defined on the model.
      #
      # should_have_instance_methods :email, :name, :name=
      #
      def should_have_instance_methods(*methods)
        get_options!(methods)
        klass = model_class
        methods.each do |method|
          should "respond to instance method ##{method}" do
            assert_respond_to klass.new, method, "#{klass.name} does not have instance method #{method}"
          end
        end
      end
 
      # Ensure that the given columns are defined on the models backing SQL table.
      #
      # should_have_db_columns :id, :email, :name, :created_at
      #
      def should_have_db_columns(*columns)
        column_type = get_options!(columns, :type)
        klass = model_class
        columns.each do |name|
          test_name = "have column #{name}"
          test_name += " of type #{column_type}" if column_type
          should test_name do
            column = klass.columns.detect {|c| c.name == name.to_s }
            assert column, "#{klass.name} does not have column #{name}"
          end
        end
      end
 
      # Ensure that the given column is defined on the models backing SQL table. The options are the same as
      # the instance variables defined on the column definition: :precision, :limit, :default, :null,
      # :primary, :type, :scale, and :sql_type.
      #
      # should_have_db_column :email, :type => "string", :default => nil, :precision => nil, :limit => 255,
      # :null => true, :primary => false, :scale => nil, :sql_type => 'varchar(255)'
      #
      def should_have_db_column(name, opts = {})
        klass = model_class
        test_name = "have column named :#{name}"
        test_name += " with options " + opts.inspect unless opts.empty?
        should test_name do
          column = klass.columns.detect {|c| c.name == name.to_s }
          assert column, "#{klass.name} does not have column #{name}"
          opts.each do |k, v|
            assert_equal column.instance_variable_get("@#{k}").to_s, v.to_s, ":#{name} column on table for #{klass} does not match option :#{k}"
          end
        end
      end
 
      # Ensures that there are DB indices on the given columns or tuples of columns.
      # Also aliased to should_have_index for readability
      #
      # should_have_indices :email, :name, [:commentable_type, :commentable_id]
      # should_have_index :age
      #
      def should_have_indices(*columns)
        table = model_class.name.tableize
        indices = ::ActiveRecord::Base.connection.indexes(table).map(&:columns)
 
        columns.each do |column|
          should "have index on #{table} for #{column.inspect}" do
            columns = [column].flatten.map(&:to_s)
            assert_contains(indices, columns)
          end
        end
      end
 
      alias_method :should_have_index, :should_have_indices
 
      # Ensures that the model cannot be saved if one of the attributes listed is not accepted.
      #
      # Options:
      # * <tt>:message</tt> - value the test expects to find in <tt>errors.on(:attribute)</tt>.
      # Regexp or string. Default = <tt>/must be accepted/</tt>
      #
      # Example:
      # should_require_acceptance_of :eula
      #
      def should_require_acceptance_of(*attributes)
        message = get_options!(attributes, :message)
        message ||= /must be accepted/
 
        attributes.each do |attribute|
          should_not_allow_values_for attribute, false, :message => message, :should => "require #{attribute} to be accepted"
        end
      end
 
      private
 
      include ThoughtBot::Shoulda::Private
    end
  end
end