aboutsummaryrefslogtreecommitdiffstats
path: root/railties/doc/guides/testing_rails_applications/testing_rails_applications.txt
blob: f8bfc66b7915da4d8ce654a57afb1ee2319674ad (plain) (blame)
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
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
A Guide to Testing Rails Applications
=====================================

This guide covers built-in mechanisms offered by Rails to test your application. By referring to this guide, you will be able to:

* Understand Rails testing terminologies
* Write unit, functional and integration tests for your application
* Read about other popular testing approaches and plugins

Assumptions:

 * You have spent more than 15 minutes in building your first application
 * The guide has been written for Rails 2.1 and above

== Why write tests for your Rails applications? ==

 * Since Ruby code that you write in your Rails application is interpreted, you may only find that its broken when you actually run your application server and use it through the browser. Writing tests is a clean way of running through your code and catching syntactical and logic errors.
 * Rails tests can also simulate browser requests and thus you can test your applications response without having to test it through your browser.
 * By simply running your Rails tests you can ensure your code adheres to the desired functionality even after some major code refactoring.
 * Rails makes it super easy to write your tests. Its starts producing skeleton code in background while you are creating your models and controllers.

== Before you start writing tests ==

=== The 3 Environments ===

Testing support was woven into the Rails fabric from the beginning. It wasn't a ``oh! let's bolt on support for running tests because they're new and cool'' epiphany.

Each Rails application you build has 3 sides. A side for production, a side for development and a side for testing.

Let's take a closer look at the Rails 'config/database.yml' file. This YAML configuration file has 3 different sections defining 3 unique database setups:

 * production
 * development
 * test

===== Why 3 different databases? =====

Well, there's one for testing where you can use sample data, there's one for development where you'll be most of the time as you develop your application, and then production for the ``real deal'', or when it goes live.

Every new Rails application should have these 3 sections filled out. They should point to different databases. You may end up not having a local database for your production environment, but development and test should both exist and be different.

===== Why Make This Distinction? =====

If you stop and think about it for a second, it makes sense.

By segregating your development database and your testing database, you're not in any danger of losing any data where it matters.

For example, you need to test your new `delete_this_user_and_every_everything_associated_with_it` function. Wouldn't you want to run this in an environment which makes no difference if you destroy data or not?

When you do end up destroying your testing database (and it will happen, trust me), simply run a task in your rakefile to rebuild it from scratch according to the specs defined in the development database. You can do this by running `rake db:test:prepare`.

=== Rails kicks-in right from the word go ===

Rails creates a test folder for you as soon as you initiate a Rails project using `rails application_name`. If you list the contents of this folder then you shall see:

[source,shell]
------------------------------------------------------
$ ls -F test/

fixtures/       functional/     integration/    test_helper.rb  unit/
------------------------------------------------------

The 'unit' folder is meant to hold tests for your models, 'functional' folder is meant to hold tests for your controllers and 'integration' folder is meant to hold tests that involves any number of controllers. Fixtures are a way of organizing data that you want to test against and reside in the 'fixtures' folder. 'test_helper.rb' holds default configuration for your tests.

=== The Lo-Down on Fixtures ===

==== What They Are ====

Fixtures is a fancy word for sample data. Fixtures allow you to populate your testing database with predefined data before your tests run. Fixtures are database independent and assume one of two formats: *YAML* or *CSV*.

You'll find fixtures under your 'test/fixtures' directory. When you run `script/generate model` to create a new model, fixture stubs will be automatically created and placed in this directory.

==== YAML the Camel is a Mammal with Enamel ====

YAML-formatted fixtures are a very human-friendly way to describe your sample data. These types of fixtures have the *.yml* file extension (as in 'users.yml').

On any given day, a YAML fixture file may look like this:

---------------------------------------------
# low & behold!  I am a YAML comment!
david:
 id: 1
 name: David Heinemeier Hansson
 birthday: 1979-10-15
 profession: Systems development

steve:
 id: 2
 name: Steve Ross Kellock
 birthday: 1974-09-27
 profession: guy with keyboard
---------------------------------------------

Each fixture is given a 'name' followed by an indented list of colon-separated key/value pairs. Records are separated by a blank space. You can place comments by using the # character in the first column.

==== Comma Seperated ====

Fixtures can also be described using the all-too-familiar comma-separated value file format. These files, just like YAML fixtures are placed in the 'test/fixtures' directory, but these end with the *.csv* file extension (as in 'celebrity_holiday_figures.csv').

A CSV fixture looks like this:

--------------------------------------------------------------
id, username, password, stretchable, comments
1, sclaus, ihatekids, false, I like to say ""Ho! Ho! Ho!""
2, ebunny, ihateeggs, true, Hoppity hop y'all
3, tfairy, ilovecavities, true, "Pull your teeth, I will"
--------------------------------------------------------------

The first line is the header. It is a comma-separated list of fields. The rest of the file is the payload: 1 record per line. A few notes about this format:

 * each cell is stripped of outward facing spaces
 * if you use a comma as data, the cell must be encased in quotes
 * if you use a quote as data, you must escape it with a 2nd quote
 * don't use blank lines
 * nulls can be achived by just placing a comma, for example, (1,sclaus,,false,) minus the parenthesis of course.

Unlike the YAML format where you give each fixture a name, CSV fixture names are automatically generated. They follow a pattern of ``model-name-counter''. In the above example, you would have:

--------------------------------------------------------------
celebrity-holiday-figures-1
celebrity-holiday-figures-2
celebrity-holiday-figures-3
--------------------------------------------------------------

The CSV format is great to use if you have existing data in a spreadsheet or database and you are able to save it (or export it) as a CSV.

==== ERb'in It Up ====

ERb allows you embed ruby code within templates. Both the YAML and CSV fixture formats are pre-processed with ERb. This allows you to use Ruby to help you generate some sample data.

I'll demonstrate with a YAML file:

--------------------------------------------------------------
<% earth_size = 20 -%>
mercury:
  id: 1
  size: <%= earth_size / 50 %>

venus:
  id: 2
  size: <%= earth_size / 2 %>

mars:
  id: 3
  size: <%= earth_size - 69 %>
--------------------------------------------------------------

Anything encased within the

-------------
<% -%>
-------------

tag is considered Ruby code. To actually print something out, you must use the

-------------
<%= %>
-------------

tag.

==== Fixtures in Action ====

Rails by default automatically loads all fixtures from the 'test/fixtures' folder for your unit and functional test. Along with which it does 3 things. Let's see an example for 'users' fixture file:
 * it nukes any existing data living in the users table
 * it loads the fixture data (if any) into the users table
 * it dumps the data into a variable in case you want to access it directly

==== Hashes with Special Powers ====

Fixtures are basically Hash objects. As mentioned in point #3 above, you can access the hash object directly because it is automatically setup as a local variable of the test case.

[source, ruby]
--------------------------------------------------------------
...
    # this will return the Hash for the fixture named david
    users(:david)

    # this will return the property for david called id
    users(:david).id
...
--------------------------------------------------------------

But, by there's another side to fixtures... at night, if the moon is full and the wind completely still, fixtures can also transform themselves into the form of the original class!

Now you can get at the methods only available to that class.

[source, ruby]
--------------------------------------------------------------
...
    # using the find method, we grab the "real" david as a User
    david = users(:david).find

    # an now we have access to methods only available to a User class
    email( david.girlfriend.email, david.illegitimate_children )
...
--------------------------------------------------------------

== Unit tests for your Models ==

In Rails, unit tests are what you write to test your models.

When you create a model using `script/generate`, among other things it creates a test stub in the 'test/unit' folder.

-------------------------------------------------------
$ script/generate model Post
...
      create  app/models/post.rb
      create  test/unit/post_test.rb
      create  test/fixtures/posts.yml
...
-------------------------------------------------------

The default test stub in 'test/unit/post_test.rb' should look like:

[source,ruby]
--------------------------------------------------

require 'test_helper'

class PostTest < ActiveSupport::TestCase
  # Replace this with your real tests.
  def test_truth
    assert true
  end
end
--------------------------------------------------

Let's examine this file line by line so that you have a clear understanding of the involved terminologies. 

`require 'test_helper'`

As you know by now that `test_helper.rb` specifies the default configuration to run our tests. This is included with all the tests. Thus any methods added to this file are available to all your tests.

`class PostTest < ActiveSupport::TestCase`

Class 'PostTest' is called a test case as it inherits from `ActiveSupport::TestCase`. 'PostTest' thus has all the methods available for ActiveSupport::TestCase. We shall look into the methods available a little later in this guide.

`def test_truth`

Any method defined within a Test Case that begins with 'test' (case sensitive) is simply called a test. So, test_password, test_valid_password and testValidPassword all are legal test names and are run automatically when the test case is run. 

`assert true`

This line of code is called an assertion. An Assertion is 1 line of code that evaluates an object (or expression) for expected results. For example, is this value = that value? is this object nil? does this line of code throw an exception? is the user's password greater than 5 characters? The assert method is available as 'PostTest' inherits from `ActiveSupport::TestCase`

A test consists of one or more assertions. Only when all the assertions are successful the test passes.

=== Running your test ===

Running a test is as simple as invoking the file through Ruby.

-------------------------------------------------------
$ cd test
$ ruby unit/post_test.rb 

Loaded suite unit/post_test
Started
.
Finished in 0.023513 seconds.

1 tests, 1 assertions, 0 failures, 0 errors
-------------------------------------------------------

This would run all the test methods from the test case.

You could also run a particular test method from the test case by using the `-n` switch with the 'test method name'

-------------------------------------------------------
$ ruby unit/post_test.rb -n test_truth

Loaded suite unit/post_test
Started
.
Finished in 0.023513 seconds.

1 tests, 1 assertions, 0 failures, 0 errors
-------------------------------------------------------

The '.' (dot) above indicates a passing test. When a test fails you see a F or if there is an error you see an E in its place. The last line of the output is the summary. 

To see how a test failure is reported, lets write a test which reports a failure. 

[source,ruby]
--------------------------------------------------
# test/unit/post_test.rb
...
  def test_should_have_atleast_one_post
    post = Post.find(:first)
    assert_not_nil post
  end
...
--------------------------------------------------

Here I am assuming you have still not added fixture data in posts.yml

Let's run this test.

-------------------------------------------------------
$ ruby unit/post_test.rb              
Loaded suite unit/post_test
Started
F.
Finished in 0.027274 seconds.

  1) Failure:
test_should_have_atleast_one_post(PostTest)
    [unit/post_test.rb:12:in `test_should_have_atleast_one_post'
     /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `__send__'
     /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `run']:
<nil> expected to not be nil.

2 tests, 2 assertions, 1 failures, 0 errors
-------------------------------------------------------

Above, 'F' denotes a failure and its corresponding trace is shown under '1)' along with the name of the test failing, which is: test_should_have_atleast_one_post(PostTest). The next few lines contain the stack trace followed by a message which mentions the actual value and the expected value by the assertion. Though, it is not highly readable it does provide us with just enough information at most times. To make the assertion failure message more readable every assertion provides an optional message parameter. Let's see the same assertion with a message parameter.

[source,ruby]
--------------------------------------------------
# test/unit/post_test.rb
...
  def test_should_have_atleast_one_post
    post = Post.find(:first)
    assert_not_nil post, "Should not be nil as Posts table should have atleast one post"
  end
...
--------------------------------------------------

Let's run this test in the console.

-------------------------------------------------------
$ ruby unit/post_test.rb
Loaded suite unit/post_test
Started
F.
Finished in 0.024727 seconds.

  1) Failure:
test_should_have_atleast_one_post(PostTest)
    [unit/post_test.rb:11:in `test_should_have_atleast_one_post'
     /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `__send__'
     /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `run']:
Should not be nil as Posts table should have atleast one post.
<nil> expected to not be nil.

2 tests, 2 assertions, 1 failures, 0 errors
-------------------------------------------------------

Now you can see an additional message in the test failure report which makes much more sense while troubleshooting. 

To see how an error is reported, let's add a test to our test case that introduces an error.

[source,ruby]
--------------------------------------------------
# test/unit/post_test.rb
...
  def test_should_report_error
    # some_undefined_variable is not defined elsewhere in the test case
    some_undefined_variable
    assert true
  end
...
--------------------------------------------------

Let's run this test in our console.

-------------------------------------------------------
$ ruby unit/post_test.rb
Loaded suite unit/post_test
Started
FE.
Finished in 0.108389 seconds.

  1) Failure:
test_should_have_atleast_one_post(PostTest)
    [unit/post_test.rb:11:in `test_should_have_atleast_one_post'
     /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `__send__'
     /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `run']:
Should not be nil as Posts table should have atleast one post.
<nil> expected to not be nil.

  2) Error:
test_should_report_error(PostTest):
NameError: undefined local variable or method `some_undefined_variable' for #<PostTest:0x304a7b0>
    /opt/local/lib/ruby/gems/1.8/gems/actionpack-2.1.1/lib/action_controller/test_process.rb:467:in `method_missing'
    unit/post_test.rb:15:in `test_should_report_error'
    /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `__send__'
    /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `run'

3 tests, 2 assertions, 1 failures, 1 errors
-------------------------------------------------------

Notice the 'E' in the output. It denotes a test with error. 

A thing to note here is that the execution of the test method is stopped as soon as an error or a assertion failure is encountered and the test suite continues with the next method. All test methods are executed in alphabetical order.

=== What to include in your Unit Tests ===

Ideally you would like to include a test for everything which could probably break. Its a good practice to have a test for each of your validations and at least 1 test for every method in your model.

=== Assertions Available ===

By now you've caught a glimpse of some of the assertions that are available. Assertions are the worker bees of testing. They are the ones that actually perform the checks to ensure things are going as planned.

There are a bunch of different types of assertions you can use. Here's the complete list of assertions that ship with test/unit. The [msg] is an optional string message you can specify to make your test failure messages clearer. It's not required.

`assert( boolean, [msg] )`::
Ensures that the object/expression is true.

`assert_equal( obj1, obj2, [msg] )`::
Ensures that `obj1 == obj2` is true.

`assert_not_equal( obj1, obj2, [msg] )`::
Ensures that `obj1 == obj2` is false.

`assert_same( obj1, obj2, [msg] )`::
Ensures that `obj1.equal?(obj2)` is true.

`assert_not_same( obj1, obj2, [msg] )`::
Ensures that `obj1.equal?(obj2)` is false.

`assert_nil( obj, [msg] )`::
Ensures that `obj.nil?` is true.

`assert_not_nil( obj, [msg] )`::
Ensures that `obj.nil?` is false.

`assert_match( regexp, string, [msg] )`::
Ensures that a string matches the regular expression.

`assert_no_match( regexp, string, [msg] )`::
Ensures that a string doesn't matches the regular expression.

`assert_in_delta( expecting, actual, delta, [msg] )`::
Ensures that the numbers `expecting` and `actual` are within `delta` of each other.

`assert_throws( symbol, [msg] ) { block }`::
Ensures that the given block throws the symbol.

`assert_raises( exception1, exception2, ... ) { block }`::
Ensures that the given block raises one of the given exceptions.

`assert_nothing_raised( exception1, exception2, ... ) { block }`::
Ensures that the given block doesn't raise one of the given exceptions.

`assert_instance_of( class, obj, [msg] )`::
Ensures that `obj` is of the `class` type.

`assert_kind_of( class, obj, [msg] )`::
Ensures that `obj` is or descends from `class`.

`assert_respond_to( obj, symbol, [msg] )`::
Ensures that obj has a method called symbol.

`assert_operator( obj1, operator, obj2, [msg] )`::
Ensures that `obj1.operator(obj2)` is true.

`assert_send( array, [msg] )`::
Ensures that executing the method listed in `array[1]` on the object in `array[0]` with the parameters of `array[2 and up]` is true. This one is weird eh?

`flunk( [msg] )`::
Ensures failure... like me and high school chemistry exams.

Because of the modular nature of the testing framework, it is possible to create your own assertions. In fact, that's exactly what Rails does. It has some specialized assertions to make your life easier.

Creating your own assertions is more of an advanced topic we won't cover in this tutorial.


=== Rails Specific Assertions ===

`assert_valid(record)`::
Ensures that the passed record is valid by Active Record standards and returns any error messages if it is not.

`assert_difference(expressions, difference = 1, message = nil) {|| ...}`::
Test numeric difference between the return value of an expression as a result of what is evaluated in the yielded block.

`assert_no_difference(expressions, message = nil, &block)`::
Assertion that the numeric result of evaluating an expression is not changed before and after invoking the passed in block.

`assert_recognizes(expected_options, path, extras={}, message=nil)`::
Asserts that the routing of the given path was handled correctly and that the parsed options (given in the expected_options hash) match path. Basically, it asserts that Rails recognizes the route given by expected_options.

`assert_generates(expected_path, options, defaults={}, extras = {}, message=nil)`::
Asserts that the provided options can be used to generate the provided path. This is the inverse of assert_recognizes. The extras parameter is used to tell the request the names and values of additional request parameters that would be in a query string. The message parameter allows you to specify a custom error message for assertion failures.

`assert_response(type, message = nil)`::
Asserts that the response is one of the following types:
 * :success - Status code was 200
 * :redirect - Status code was in the 300-399 range
 * :missing - Status code was 404
 * :error - Status code was in the 500-599 range
 
`assert_redirected_to(options = {}, message=nil)`::
Assert that the redirection options passed in match those of the redirect called in the latest action. This match can be partial, such that assert_redirected_to(:controller => "weblog") will also match the redirection of redirect_to(:controller => "weblog", :action => "show") and so on.

`assert_template(expected = nil, message=nil)`::
Asserts that the request was rendered with the appropriate template file.

You would get to see the usage of some of these assertions in the next chapter.

== Functional tests for your Controllers ==

In Rails, testing various actions of a single controller is termed as writing functional tests for that controller. Controllers handle the incoming web requests to your application and eventually respond with a rendered view. 

=== What to include in your Functional Tests ===

You should test for things such as:

 * was the web request successful?
 * were we redirected to the right page?
 * were we successfully authenticated?
 * was the correct object stored in the response template?
 * was the appropriate message displayed to the user in the view

When you use `script/generate` to create a controller, it automatically creates a functional test for that controller in 'test/functional'. Let's create a post controller:

-------------------------------------------------------
$ script/generate controller post
...
      create  app/controllers/post_controller.rb
      create  test/functional/post_controller_test.rb
...
-------------------------------------------------------

Now if you take a look at the file 'posts_controller_test.rb' in the 'test/functional' directory, you should see:

[source,ruby]
--------------------------------------------------
require 'test_helper'

class PostsControllerTest < ActionController::TestCase
  # Replace this with your real tests.
  def test_truth
    assert true
  end
end
--------------------------------------------------


Example functional tests for posts controller:

[source,ruby]
--------------------------------------------------
  def test_should_get_index
    get :index
    assert_response :success
    assert_not_nil assigns(:posts)
  end
--------------------------------------------------


In the test_should_get_index test, we are simulating a request on the action called index, making sure the request was successful and also ensuring that it assigns a valid `posts` instance variable. 

The get method kicks off the web request and populates the results into the response. It accepts 4 arguments.

 * The action of the controller you are requesting. It can be in the form of a string or a symbol. 
 * An optional hash of request parameters to pass into the action (eg. query string parameters or post variables).
 * An optional hash of session variables to pass along with the request.
 * An optional hash of flash to stash your goulash.

Example: Calling the :show action, passing an id of 12 as the params and setting user_id of 5 in the session.

get(:show, {'id' => "12"}, {'user_id' => 5})

Another example: Calling the :view action, passing an id of 12 as the params, this time with no session, but with a flash message.

get(:view, {'id' => '12'}, nil, {'message' => 'booya!'})

=== Available request types at your disposal ===

For those of you familiar with HTTP protocol, you'll know that get is a type of request. There are 5 request types supported in Rails:

 * get
 * post
 * put
 * head
 * delete

All of request types are methods that you can use, however, you'll probably end up using the first two more often than the others.

=== The 4 Hashes of the Apocolypse ===

After the request has been made by using one of the 5 methods (get, post, etc…), you will have 4 Hash objects ready for use.

They are (starring in alphabetical order):

`assigns`::
Any objects that are stored as instance variables in actions for use in views.

`cookies`::
Any objects cookies that are set.

`flash`::
Any objects living in the flash.

`session`::
Any object living in session variables.

As is the case with normal Hash objects, you can access the values by referencing the keys by string. You can also reference them by symbol name… except assigns. Check it out:

  flash["gordon"]               flash[:gordon]
  session["shmession"]          session[:shmession]
  cookies["are_good_for_u"]     cookies[:are_good_for_u]

# Because you can't use assigns[:something] for historical reasons:
  assigns["something"]          assigns(:something)

=== Instance variables available ===

 * `@controller`
 * `@request`
 * `@response`

Another example that uses flash, assert_redirected_to, assert_difference

[source,ruby]
--------------------------------------------------
  def test_should_create_post
    assert_difference('Post.count') do
      post :create, :post => { :title => 'Hi', :body => 'This is my first post.'}
    end
    assert_redirected_to post_path(assigns(:post))
    assert_equal 'Post was successfully created.', flash[:notice]
  end
--------------------------------------------------

=== Testing Views ===

Testing the response to your request by asserting the presence of key html elements and their content is a good practice. `assert_select` allows you to do all this by using a simple yet powerful syntax.

[NOTE]
`assert_tag` is now deprecated in favor of `assert_select`

`assert_select(selector, [equality], [message])`::
Ensures that the equality condition is met on the selected elements through the selector. The selector may be a CSS selector expression (String), an expression with substitution values, or an HTML::Selector object.

`assert_select(element, selector, [equality], [message])`::
Ensures that the equality condition is met on all the selected elements through the selector starting from the _element_ (instance of HTML::Node) and its descendants.

For example, you could verify the contents on the title element in your response with:

[source,ruby]
--------------------------------------------------
assert_select 'title', "Welcome to Rails Testing Guide"
--------------------------------------------------

You can also use nested `assert_select` blocks. In this case the inner `assert_select` will run the assertion on each element selected by the outer `assert_select` block.

[source,ruby]
--------------------------------------------------
assert_select 'ul.navigation' do
  assert_select 'li.menu_item'
end
--------------------------------------------------

`assert_select` is really powerful and I would recommend you to go through its http://api.rubyonrails.com/classes/ActionController/Assertions/SelectorAssertions.html#M000749[documentation] for its advanced usage.

==== Additional view based assertions ====

`assert_select_email`::
Allows you to make assertions on the body of an e-mail. 

[source,ruby]
--------------------------------------------------
assert_select_email do
  assert_select 'small', 'Please click the "Unsubscribe" link if you want to opt-out.'
end
--------------------------------------------------

`assert_select_rjs`::
Allows you to make assertions on RJS response. `assert_select_rjs` has variants which allow you to narrow down upon the updated element or event a particular operation on an element.

`assert_select_encoded`::
Allows you to make assertions on encoded HTML. It does this by un-encoding the contents of each element and then calling the block with all the un-encoded elements.

`css_select(selector)`::
`css_select(element, selector)`::
Returns an array of all the elements selected by the _selector_. In the second variant it first matches the base _element_ and tries to match the _selector_ expression on any of its children. If there are no matches both variants return an empty array.

== Integration Testing ==

Integration tests are used to test interaction among any number of controllers. They are generally used to test important work flows within your application. 

Unlike Unit and Functional tests they have to be explicitly created under the 'test/integration' folder within our application. Rails provides a generator to create an integration test skeleton for you. 

Example:

--------------------------------------------------
$ script/generate integration_test create_blog_and_then_post_comments
      exists  test/integration/
      create  test/integration/create_blog_and_then_post_comments_test.rb
--------------------------------------------------

[source,ruby]
--------------------------------------------------
require 'test_helper'

class CreateBlogAndThenPostCommentsTest < ActionController::IntegrationTest
  # fixtures :your, :models

  # Replace this with your real tests.
  def test_truth
    assert true
  end
end
--------------------------------------------------

=== Differences in comparison to unit and functional tests ===

* You will have to include fixtures explicitly unlike unit and functional tests in which all the fixtures are loaded by default (through test_helper)
* Additional helpers: https?, https!, host!, follow_redirect!, post/get_via_redirect, open_session, reset

== Rake Tasks for Testing

The table below lists all rake tasks that come along in the default Rakefile when you initiate a Rail project.

.Default Rake tasks
[grid="all"]
-------------------------
Tasks Description
-------------------------
`rake test`                     Runs all unit, functional and integration tests. You can also simply run `rake` as _test_ target is default.
`rake test:units`               Runs all the unit tests from 'test/unit'
`rake test:functionals`         Runs all the functional tests from 'test/functional'
`rake test:integration`         Runs all the integration tests from 'test/integration'
`rake test:recent`              Tests recent changes
`rake test:uncommitted`         Runs all the tests which are uncommitted. Only supports Subversion
`rake test:plugins`             Run all the plugin tests from vendor/plugins/*/**/test (or specify with `PLUGIN=_name_`)
`rake db:test:clone`            Recreate the test database from the current environment's database schema
`rake db:test:clone_structure`  Recreate the test databases from the development structure
`rake db:test:load`             Recreate the test database from the current schema.rb
`rake db:test:prepare`          Check for pending migrations and load the test schema
`rake db:test:purge`            Empty the test database.
-------------------------

TIP: You can see all these rake task and their descriptions by running `rake --tasks --describe`

== Testing Your Mailers ==

=== Keeping the postman in check ===

Your ActionMailer -- like every other part of your Rails application -- should be tested to ensure that it is working as expected.

The goal of testing your ActionMailer is to ensure that:

 * emails are being processed (created and sent)
 * the email content is correct (subject, sender, body, etc)
 * the right emails are being sent at the righ times

==== From all sides ====

There are two aspects of testing your mailer, the unit tests and the functional tests.
Unit tests

In the unit tests, we run the mailer in isolation with tightly controlled inputs and compare the output to a known-value -- a fixture -- yay! more fixtures!

==== Functional tests ====

In the functional tests we don't so much test the minute details produced by the mailer, instead we test that our controllers and models are using the mailer in the right way. We test to prove that the right email was sent at the right time.

=== Unit Testing ===

In order to test that your mailer is working as expected, we can use unit tests to compare the actual results of the mailer with pre-writen examples of what should be produced.

==== Revenge of the fixtures ====

For the purposes of unit testing a mailer, fixtures are used to provide an example of how output ``should'' look. Because these are example emails, and not Active Record data like the other fixtures, they are kept in their own subdirectory from the other fixtures. Don't tease them about it though, they hate that.

When you generated your mailer (you did that right?) the generator created stub fixtures for each of the mailers actions. If you didn't use the generator you'll have to make those files yourself.

==== The basic test case ====

Here is an example of what you start with.

[source, ruby]
-------------------------------------------------
require File.dirname(__FILE__) + '/. ./test_helper'

class MyMailerTest < Test::Unit::TestCase
  FIXTURES_PATH = File.dirname(__FILE__) + '/. ./fixtures'

  def setup
    ActionMailer::Base.delivery_method = :test
    ActionMailer::Base.perform_deliveries = true
    ActionMailer::Base.deliveries = []

    @expected = TMail::Mail.new
  end

  def test_signup
    @expected.subject = 'MyMailer#signup'
    @expected.body    = read_fixture('signup')
    @expected.date    = Time.now

    assert_equal @expected.encoded, MyMailer.create_signup(@expected.date).encoded
  end

  private
    def read_fixture(action)
      IO.readlines("#{FIXTURES_PATH}/my_mailer/#{action}")
    end
end
-------------------------------------------------

The `setup` method is mostly concerned with setting up a blank slate for the next test. However it is worth describing what each statement does

[source, ruby]
-------------------------------------------------
ActionMailer::Base.delivery_method = :test
-------------------------------------------------

sets the delivery method to test mode so that email will not actually be delivered (useful to avoid spamming your users while testing) but instead it will be appended to an array (ActionMailer::Base.deliveries).

[source, ruby]
-------------------------------------------------
ActionMailer::Base.perform_deliveries = true
-------------------------------------------------

Ensures the mail will be sent using the method specified by ActionMailer::Base.delivery_method, and finally

[source, ruby]
-------------------------------------------------
ActionMailer::Base.deliveries = []
-------------------------------------------------

sets the array of sent messages to an empty array so we can be sure that anything we find there was sent as part of our current test.

However often in unit tests, mails will not actually be sent, simply constructed, as in the example above, where the precise content of the email is checked against what it should be. Dave Thomas suggests an alternative approach, which is just to check the part of the email that is likely to break, i.e. the dynamic content. The following example assumes we have some kind of user table, and we might want to mail those users new passwords:

[source, ruby]
-------------------------------------------------
require File.dirname(__FILE__) + '/../test_helper'
require 'my_mailer'

class MyMailerTest < Test::Unit::TestCase
  fixtures :users
  FIXTURES_PATH = File.dirname(__FILE__) + '/../fixtures'
  CHARSET = "utf-8"

  include ActionMailer::Quoting

  def setup
    ActionMailer::Base.delivery_method = :test
    ActionMailer::Base.perform_deliveries = true
    ActionMailer::Base.deliveries = []

    @expected = TMail::Mail.new
    @expected.set_content_type "text", "plain", { "charset" => CHARSET }
  end

  def test_reset_password
    user = User.find(:first)
    newpass = 'newpass'
    response = MyMailer.create_reset_password(user,newpass)
    assert_equal 'Your New Password', response.subject
    assert_match /Dear #{user.full_name},/, response.body
    assert_match /New Password: #{newpass}/, response.body
    assert_equal user.email, response.to[0]
  end

  private
    def read_fixture(action)
      IO.readlines("#{FIXTURES_PATH}/community_mailer/#{action}")
    end

    def encode(subject)
      quoted_printable(subject, CHARSET)
    end
end
-------------------------------------------------

and here we check the dynamic parts of the mail, specifically that we use the users' correct full name and that we give them the correct password.

=== Functional Testing ===

Functional testing involves more than just checking that the email body, recipients and so forth are correct. In functional mail tests we call the mail deliver methods and check that the appropriate emails have been appended to the delivery list. It is fairly safe to assume that the deliver methods themselves do their job -- what we are probably more interested in is whether our own business logic is sending emails when we expect them to. For example the password reset operation we used an example in the previous section will probably be called in response to a user requesting a password reset through some sort of controller.

[source, ruby]
----------------------------------------------------------------
require File.dirname(__FILE__) + '/../test_helper'
require 'my_controller'

# Raise errors beyond the default web-based presentation
class MyController; def rescue_action(e) raise e end; end

class MyControllerTest < Test::Unit::TestCase

  def setup
    @controller = MyController.new
    @request, @response = ActionController::TestRequest.new, ActionController::TestResponse.new
  end

  def test_reset_password
    num_deliveries = ActionMailer::Base.deliveries.size
    post :reset_password, :email => 'bob@test.com'

    assert_equal num_deliveries+1, ActionMailer::Base.deliveries.size
  end

end
----------------------------------------------------------------

== Guide TODO ==
 * Describe _setup_ and _teardown_
 * Examples for integration test
 * Updating the section on testing mailers