rails 2.3.2 → 2.3.3

Sign up to get free protection for your applications and to get access to all the features.

Potentially problematic release.


This version of rails might be problematic. Click here for more details.

Files changed (118) hide show
  1. data/CHANGELOG +4 -0
  2. data/Rakefile +11 -9
  3. data/configs/routes.rb +1 -1
  4. data/guides/files/javascripts/code_highlighter.js +188 -0
  5. data/guides/files/javascripts/guides.js +8 -0
  6. data/guides/files/javascripts/highlighters.js +90 -0
  7. data/guides/files/stylesheets/main.css +441 -0
  8. data/guides/files/stylesheets/print.css +52 -0
  9. data/guides/files/stylesheets/reset.css +43 -0
  10. data/guides/files/stylesheets/style.css +13 -0
  11. data/guides/files/stylesheets/syntax.css +31 -0
  12. data/guides/images/belongs_to.png +0 -0
  13. data/guides/images/book_icon.gif +0 -0
  14. data/guides/images/bullet.gif +0 -0
  15. data/guides/images/chapters_icon.gif +0 -0
  16. data/guides/images/check_bullet.gif +0 -0
  17. data/guides/images/credits_pic_blank.gif +0 -0
  18. data/guides/images/csrf.png +0 -0
  19. data/guides/images/customized_error_messages.png +0 -0
  20. data/guides/images/error_messages.png +0 -0
  21. data/guides/images/feature_tile.gif +0 -0
  22. data/guides/images/footer_tile.gif +0 -0
  23. data/guides/images/fxn.jpg +0 -0
  24. data/guides/images/grey_bullet.gif +0 -0
  25. data/guides/images/habtm.png +0 -0
  26. data/guides/images/has_many.png +0 -0
  27. data/guides/images/has_many_through.png +0 -0
  28. data/guides/images/has_one.png +0 -0
  29. data/guides/images/has_one_through.png +0 -0
  30. data/guides/images/header_backdrop.png +0 -0
  31. data/guides/images/header_tile.gif +0 -0
  32. data/guides/images/i18n/demo_localized_pirate.png +0 -0
  33. data/guides/images/i18n/demo_translated_en.png +0 -0
  34. data/guides/images/i18n/demo_translated_pirate.png +0 -0
  35. data/guides/images/i18n/demo_translation_missing.png +0 -0
  36. data/guides/images/i18n/demo_untranslated.png +0 -0
  37. data/guides/images/icons/README +5 -0
  38. data/guides/images/icons/callouts/1.png +0 -0
  39. data/guides/images/icons/callouts/10.png +0 -0
  40. data/guides/images/icons/callouts/11.png +0 -0
  41. data/guides/images/icons/callouts/12.png +0 -0
  42. data/guides/images/icons/callouts/13.png +0 -0
  43. data/guides/images/icons/callouts/14.png +0 -0
  44. data/guides/images/icons/callouts/15.png +0 -0
  45. data/guides/images/icons/callouts/2.png +0 -0
  46. data/guides/images/icons/callouts/3.png +0 -0
  47. data/guides/images/icons/callouts/4.png +0 -0
  48. data/guides/images/icons/callouts/5.png +0 -0
  49. data/guides/images/icons/callouts/6.png +0 -0
  50. data/guides/images/icons/callouts/7.png +0 -0
  51. data/guides/images/icons/callouts/8.png +0 -0
  52. data/guides/images/icons/callouts/9.png +0 -0
  53. data/guides/images/icons/caution.png +0 -0
  54. data/guides/images/icons/example.png +0 -0
  55. data/guides/images/icons/home.png +0 -0
  56. data/guides/images/icons/important.png +0 -0
  57. data/guides/images/icons/next.png +0 -0
  58. data/guides/images/icons/note.png +0 -0
  59. data/guides/images/icons/prev.png +0 -0
  60. data/guides/images/icons/tip.png +0 -0
  61. data/guides/images/icons/up.png +0 -0
  62. data/guides/images/icons/warning.png +0 -0
  63. data/guides/images/nav_arrow.gif +0 -0
  64. data/guides/images/polymorphic.png +0 -0
  65. data/guides/images/posts_index.png +0 -0
  66. data/guides/images/rails_guides_logo.gif +0 -0
  67. data/guides/images/rails_logo_remix.gif +0 -0
  68. data/guides/images/rails_welcome.png +0 -0
  69. data/guides/images/session_fixation.png +0 -0
  70. data/guides/images/tab_grey.gif +0 -0
  71. data/guides/images/tab_info.gif +0 -0
  72. data/guides/images/tab_note.gif +0 -0
  73. data/guides/images/tab_red.gif +0 -0
  74. data/guides/images/tab_yellow.gif +0 -0
  75. data/guides/images/tab_yellow.png +0 -0
  76. data/guides/images/validation_error_messages.png +0 -0
  77. data/guides/rails_guides.rb +42 -0
  78. data/guides/rails_guides/generator.rb +138 -0
  79. data/guides/rails_guides/helpers.rb +34 -0
  80. data/guides/rails_guides/indexer.rb +55 -0
  81. data/guides/rails_guides/textile_extensions.rb +41 -0
  82. data/guides/source/2_2_release_notes.textile +422 -0
  83. data/guides/source/2_3_release_notes.textile +610 -0
  84. data/guides/source/action_controller_overview.textile +776 -0
  85. data/guides/source/action_mailer_basics.textile +424 -0
  86. data/guides/source/active_record_basics.textile +135 -0
  87. data/guides/source/active_record_querying.textile +969 -0
  88. data/guides/source/activerecord_validations_callbacks.textile +1086 -0
  89. data/guides/source/association_basics.textile +1781 -0
  90. data/guides/source/caching_with_rails.textile +524 -0
  91. data/guides/source/command_line.textile +589 -0
  92. data/guides/source/configuring.textile +234 -0
  93. data/guides/source/contribute.textile +71 -0
  94. data/guides/source/contributing_to_rails.textile +239 -0
  95. data/guides/source/credits.erb.textile +52 -0
  96. data/guides/source/debugging_rails_applications.textile +709 -0
  97. data/guides/source/form_helpers.textile +766 -0
  98. data/guides/source/getting_started.textile +1297 -0
  99. data/guides/source/i18n.textile +912 -0
  100. data/guides/source/index.erb.textile +124 -0
  101. data/guides/source/layout.html.erb +103 -0
  102. data/guides/source/layouts_and_rendering.textile +979 -0
  103. data/guides/source/migrations.textile +591 -0
  104. data/guides/source/nested_model_forms.textile +222 -0
  105. data/guides/source/performance_testing.textile +531 -0
  106. data/guides/source/plugins.textile +1512 -0
  107. data/guides/source/rails_on_rack.textile +309 -0
  108. data/guides/source/routing.textile +903 -0
  109. data/guides/source/security.textile +986 -0
  110. data/guides/source/testing.textile +951 -0
  111. data/lib/commands/performance/profiler.rb +1 -1
  112. data/lib/initializer.rb +27 -4
  113. data/lib/rails/gem_dependency.rb +35 -6
  114. data/lib/rails/rack/metal.rb +1 -1
  115. data/lib/rails/version.rb +1 -1
  116. data/lib/tasks/gems.rake +19 -6
  117. data/lib/test_help.rb +4 -1
  118. metadata +123 -7
@@ -0,0 +1,951 @@
1
+ h2. A Guide to Testing Rails Applications
2
+
3
+ This guide covers built-in mechanisms offered by Rails to test your application. By referring to this guide, you will be able to:
4
+
5
+ * Understand Rails testing terminology
6
+ * Write unit, functional and integration tests for your application
7
+ * Identify other popular testing approaches and plugins
8
+
9
+ This guide won't teach you to write a Rails application; it assumes basic familiarity with the Rails way of doing things.
10
+
11
+ endprologue.
12
+
13
+ h3. Why Write Tests for your Rails Applications?
14
+
15
+ * Rails makes it super easy to write your tests. It starts by producing skeleton test code in background while you are creating your models and controllers.
16
+ * By simply running your Rails tests you can ensure your code adheres to the desired functionality even after some major code refactoring.
17
+ * Rails tests can also simulate browser requests and thus you can test your application's response without having to test it through your browser.
18
+
19
+ h3. Introduction to Testing
20
+
21
+ Testing support was woven into the Rails fabric from the beginning. It wasn't an "oh! let's bolt on support for running tests because they're new and cool" epiphany. Just about every Rails application interacts heavily with a database - and, as a result, your tests will need a database to interact with as well. To write efficient tests, you'll need to understand how to set up this database and populate it with sample data.
22
+
23
+ h4. The Three Environments
24
+
25
+ Every Rails application you build has 3 sides: a side for production, a side for development, and a side for testing.
26
+
27
+ One place you'll find this distinction is in the +config/database.yml+ file. This YAML configuration file has 3 different sections defining 3 unique database setups:
28
+
29
+ * production
30
+ * development
31
+ * test
32
+
33
+ This allows you to set up and interact with test data without any danger of your tests altering data from your production environment.
34
+
35
+ For example, suppose 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 where it makes no difference if you destroy data or not?
36
+
37
+ When you do end up destroying your testing database (and it will happen, trust me), you can rebuild it from scratch according to the specs defined in the development database. You can do this by running +rake db:test:prepare+.
38
+
39
+ h4. Rails Sets up for Testing from the Word Go
40
+
41
+ Rails creates a +test+ folder for you as soon as you create a Rails project using +rails _application_name_+. If you list the contents of this folder then you shall see:
42
+
43
+ <shell>
44
+ $ ls -F test/
45
+
46
+ fixtures/ functional/ integration/ test_helper.rb unit/
47
+ </shell>
48
+
49
+ The +unit+ folder is meant to hold tests for your models, the +functional+ folder is meant to hold tests for your controllers, and the +integration+ folder is meant to hold tests that involve any number of controllers interacting. Fixtures are a way of organizing test data; they reside in the +fixtures+ folder. The +test_helper.rb+ file holds the default configuration for your tests.
50
+
51
+ h4. The Low-Down on Fixtures
52
+
53
+ For good tests, you'll need to give some thought to setting up test data. In Rails, you can handle this by defining and customizing fixtures.
54
+
55
+ h5. What are Fixtures?
56
+
57
+ _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*. In this guide we will use *YAML* which is the preferred format.
58
+
59
+ 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.
60
+
61
+ h5. YAML
62
+
63
+ 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+).
64
+
65
+ Here's a sample YAML fixture file:
66
+
67
+ <yaml>
68
+ # low & behold! I am a YAML comment!
69
+ david:
70
+ name: David Heinemeier Hansson
71
+ birthday: 1979-10-15
72
+ profession: Systems development
73
+
74
+ steve:
75
+ name: Steve Ross Kellock
76
+ birthday: 1974-09-27
77
+ profession: guy with keyboard
78
+ </yaml>
79
+
80
+ 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 in a fixture file by using the # character in the first column.
81
+
82
+ h5. ERb'in It Up
83
+
84
+ ERb allows you embed ruby code within templates. Both the YAML and CSV fixture formats are pre-processed with ERb when you load fixtures. This allows you to use Ruby to help you generate some sample data.
85
+
86
+ <erb>
87
+ <% earth_size = 20 -%>
88
+ mercury:
89
+ size: <%= earth_size / 50 %>
90
+ brightest_on: <%= 113.days.ago.to_s(:db) %>
91
+
92
+ venus:
93
+ size: <%= earth_size / 2 %>
94
+ brightest_on: <%= 67.days.ago.to_s(:db) %>
95
+
96
+ mars:
97
+ size: <%= earth_size - 69 %>
98
+ brightest_on: <%= 13.days.from_now.to_s(:db) %>
99
+ </erb>
100
+
101
+ Anything encased within the
102
+
103
+ <erb>
104
+ <% %>
105
+ </erb>
106
+
107
+ tag is considered Ruby code. When this fixture is loaded, the +size+ attribute of the three records will be set to 20/50, 20/2, and 20-69 respectively. The +brightest_on+ attribute will also be evaluated and formatted by Rails to be compatible with the database.
108
+
109
+ h5. Fixtures in Action
110
+
111
+ Rails by default automatically loads all fixtures from the 'test/fixtures' folder for your unit and functional test. Loading involves three steps:
112
+
113
+ * Remove any existing data from the table corresponding to the fixture
114
+ * Load the fixture data into the table
115
+ * Dump the fixture data into a variable in case you want to access it directly
116
+
117
+ h5. Hashes with Special Powers
118
+
119
+ 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. For example:
120
+
121
+ <ruby>
122
+ # this will return the Hash for the fixture named david
123
+ users(:david)
124
+
125
+ # this will return the property for david called id
126
+ users(:david).id
127
+ </ruby>
128
+
129
+ Fixtures can also transform themselves into the form of the original class. Thus, you can get at the methods only available to that class.
130
+
131
+ <ruby>
132
+ # using the find method, we grab the "real" david as a User
133
+ david = users(:david).find
134
+
135
+ # and now we have access to methods only available to a User class
136
+ email(david.girlfriend.email, david.location_tonight)
137
+ </ruby>
138
+
139
+ h3. Unit Testing your Models
140
+
141
+ In Rails, unit tests are what you write to test your models.
142
+
143
+ For this guide we will be using Rails _scaffolding_. It will create the model, a migration, controller and views for the new resource in a single operation. It will also create a full test suite following Rails best practices. I will be using examples from this generated code and would be supplementing it with additional examples where necessary.
144
+
145
+ NOTE: For more information on Rails _scaffolding_, refer to "Getting Started with Rails":getting_started.html
146
+
147
+ When you use +script/generate scaffold+, for a resource among other things it creates a test stub in the +test/unit+ folder:
148
+
149
+ <pre>
150
+ $ script/generate scaffold post title:string body:text
151
+ ...
152
+ create app/models/post.rb
153
+ create test/unit/post_test.rb
154
+ create test/fixtures/posts.yml
155
+ ...
156
+ </pre>
157
+
158
+ The default test stub in +test/unit/post_test.rb+ looks like this:
159
+
160
+ <ruby>
161
+ require 'test_helper'
162
+
163
+ class PostTest < ActiveSupport::TestCase
164
+ # Replace this with your real tests.
165
+ def test_truth
166
+ assert true
167
+ end
168
+ end
169
+ </ruby>
170
+
171
+ A line by line examination of this file will help get you oriented to Rails testing code and terminology.
172
+
173
+ <ruby>
174
+ require 'test_helper'
175
+ </ruby>
176
+
177
+ As you know by now that +test_helper.rb+ specifies the default configuration to run our tests. This is included with all the tests, so any methods added to this file are available to all your tests.
178
+
179
+ <ruby>
180
+ class PostTest < ActiveSupport::TestCase
181
+ </ruby>
182
+
183
+ The +PostTest+ class defines a _test case_ because it inherits from +ActiveSupport::TestCase+. +PostTest+ thus has all the methods available from +ActiveSupport::TestCase+. You'll see those methods a little later in this guide.
184
+
185
+ <ruby>
186
+ def test_truth
187
+ </ruby>
188
+
189
+ 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.
190
+
191
+ <ruby>
192
+ assert true
193
+ </ruby>
194
+
195
+ This line of code is called an _assertion_. An assertion is a line of code that evaluates an object (or expression) for expected results. For example, an assertion can check:
196
+
197
+ * is this value = that value?
198
+ * is this object nil?
199
+ * does this line of code throw an exception?
200
+ * is the user's password greater than 5 characters?
201
+
202
+ Every test contains one or more assertions. Only when all the assertions are successful the test passes.
203
+
204
+ h4. Preparing your Application for Testing
205
+
206
+ Before you can run your tests you need to ensure that the test database structure is current. For this you can use the following rake commands:
207
+
208
+ <shell>
209
+ $ rake db:migrate
210
+ ...
211
+ $ rake db:test:load
212
+ </shell>
213
+
214
+ Above +rake db:migrate+ runs any pending migrations on the _developemnt_ environment and updates +db/schema.rb+. +rake db:test:load+ recreates the test database from the current db/schema.rb. On subsequent attempts it is a good to first run +db:test:prepare+ as it first checks for pending migrations and warns you appropriately.
215
+
216
+ NOTE: +db:test:prepare+ will fail with an error if db/schema.rb doesn't exists.
217
+
218
+ h5. Rake Tasks for Preparing your Application for Testing
219
+
220
+ |_.Tasks |_.Description|
221
+ |+rake db:test:clone+ |Recreate the test database from the current environment's database schema|
222
+ |+rake db:test:clone_structure+ |Recreate the test databases from the development structure|
223
+ |+rake db:test:load+ |Recreate the test database from the current +schema.rb+|
224
+ |+rake db:test:prepare+ |Check for pending migrations and load the test schema|
225
+ |+rake db:test:purge+ |Empty the test database.|
226
+
227
+ TIP: You can see all these rake tasks and their descriptions by running +rake --tasks --describe+
228
+
229
+ h4. Running Tests
230
+
231
+ Running a test is as simple as invoking the file containing the test cases through Ruby:
232
+
233
+ <shell>
234
+ $ cd test
235
+ $ ruby unit/post_test.rb
236
+
237
+ Loaded suite unit/post_test
238
+ Started
239
+ .
240
+ Finished in 0.023513 seconds.
241
+
242
+ 1 tests, 1 assertions, 0 failures, 0 errors
243
+ </shell>
244
+
245
+ This will run all the test methods from the test case.
246
+
247
+ You can also run a particular test method from the test case by using the +-n+ switch with the +test method name+.
248
+
249
+ <pre>
250
+ $ ruby unit/post_test.rb -n test_truth
251
+
252
+ Loaded suite unit/post_test
253
+ Started
254
+ .
255
+ Finished in 0.023513 seconds.
256
+
257
+ 1 tests, 1 assertions, 0 failures, 0 errors
258
+ </pre>
259
+
260
+ The +.+ (dot) above indicates a passing test. When a test fails you see an +F+; when a test throws an error you see an +E+ in its place. The last line of the output is the summary.
261
+
262
+ To see how a test failure is reported, you can add a failing test to the +post_test.rb+ test case.
263
+
264
+ <ruby>
265
+ def test_should_not_save_post_without_title
266
+ post = Post.new
267
+ assert !post.save
268
+ end
269
+ </ruby>
270
+
271
+ Let us run this newly added test.
272
+
273
+ <pre>
274
+ $ ruby unit/post_test.rb -n test_should_not_save_post_without_title
275
+ Loaded suite unit/post_test
276
+ Started
277
+ F
278
+ Finished in 0.197094 seconds.
279
+
280
+ 1) Failure:
281
+ test_should_not_save_post_without_title(PostTest)
282
+ [unit/post_test.rb:11:in `test_should_not_save_post_without_title'
283
+ /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `__send__'
284
+ /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `run']:
285
+ <false> is not true.
286
+
287
+ 1 tests, 1 assertions, 1 failures, 0 errors
288
+ </pre>
289
+
290
+ In the output, +F+ denotes a failure. You can see the corresponding trace shown under +1)+ along with the name of the failing test. The next few lines contain the stack trace followed by a message which mentions the actual value and the expected value by the assertion. The default assertion messages provide just enough information to help pinpoint the error. To make the assertion failure message more readable every assertion provides an optional message parameter, as shown here:
291
+
292
+ <ruby>
293
+ def test_should_not_save_post_without_title
294
+ post = Post.new
295
+ assert !post.save, "Saved the post without a title"
296
+ end
297
+ </ruby>
298
+
299
+ Running this test shows the friendlier assertion message:
300
+
301
+ <pre>
302
+ $ ruby unit/post_test.rb -n test_should_not_save_post_without_title
303
+ Loaded suite unit/post_test
304
+ Started
305
+ F
306
+ Finished in 0.198093 seconds.
307
+
308
+ 1) Failure:
309
+ test_should_not_save_post_without_title(PostTest)
310
+ [unit/post_test.rb:11:in `test_should_not_save_post_without_title'
311
+ /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `__send__'
312
+ /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `run']:
313
+ Saved the post without a title.
314
+ <false> is not true.
315
+
316
+ 1 tests, 1 assertions, 1 failures, 0 errors
317
+ </pre>
318
+
319
+ Now to get this test to pass we can add a model level validation for the _title_ field.
320
+
321
+ <ruby>
322
+ class Post < ActiveRecord::Base
323
+ validates_presence_of :title
324
+ end
325
+ </ruby>
326
+
327
+ Now the test should pass. Let us verify by running the test again:
328
+
329
+ <pre>
330
+ $ ruby unit/post_test.rb -n test_should_not_save_post_without_title
331
+ Loaded suite unit/post_test
332
+ Started
333
+ .
334
+ Finished in 0.193608 seconds.
335
+
336
+ 1 tests, 1 assertions, 0 failures, 0 errors
337
+ </pre>
338
+
339
+ Now if you noticed we first wrote a test which fails for a desired functionality, then we wrote some code which adds the functionality and finally we ensured that our test passes. This approach to software development is referred to as _Test-Driven Development_ (TDD).
340
+
341
+ TIP: Many Rails developers practice _Test-Driven Development_ (TDD). This is an excellent way to build up a test suite that exercises every part of your application. TDD is beyond the scope of this guide, but one place to start is with "15 TDD steps to create a Rails application":http://andrzejonsoftware.blogspot.com/2007/05/15-tdd-steps-to-create-rails.html.
342
+
343
+ To see how an error gets reported, here's a test containing an error:
344
+
345
+ <ruby>
346
+ def test_should_report_error
347
+ # some_undefined_variable is not defined elsewhere in the test case
348
+ some_undefined_variable
349
+ assert true
350
+ end
351
+ </ruby>
352
+
353
+ Now you can see even more output in the console from running the tests:
354
+
355
+ <pre>
356
+ $ ruby unit/post_test.rb -n test_should_report_error
357
+ Loaded suite unit/post_test
358
+ Started
359
+ E
360
+ Finished in 0.195757 seconds.
361
+
362
+ 1) Error:
363
+ test_should_report_error(PostTest):
364
+ NameError: undefined local variable or method `some_undefined_variable' for #<PostTest:0x2cc9de8>
365
+ /opt/local/lib/ruby/gems/1.8/gems/actionpack-2.1.1/lib/action_controller/test_process.rb:467:in `method_missing'
366
+ unit/post_test.rb:16:in `test_should_report_error'
367
+ /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `__send__'
368
+ /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `run'
369
+
370
+ 1 tests, 0 assertions, 0 failures, 1 errors
371
+ </pre>
372
+
373
+ Notice the 'E' in the output. It denotes a test with error.
374
+
375
+ NOTE: The execution of each test method stops as soon as any error or a assertion failure is encountered, and the test suite continues with the next method. All test methods are executed in alphabetical order.
376
+
377
+ h4. What to Include in Your Unit Tests
378
+
379
+ Ideally you would like to include a test for everything which could possibly break. It's a good practice to have at least one test for each of your validations and at least one test for every method in your model.
380
+
381
+ h4. Assertions Available
382
+
383
+ 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 that things are going as planned.
384
+
385
+ 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 testing library used by Rails. The +[msg]+ parameter is an optional string message you can specify to make your test failure messages clearer. It's not required.
386
+
387
+ |_.Assertion |_.Purpose|
388
+ |+assert( boolean, [msg] )+ |Ensures that the object/expression is true.|
389
+ |+assert_equal( obj1, obj2, [msg] )+ |Ensures that +obj1 == obj2+ is true.|
390
+ |+assert_not_equal( obj1, obj2, [msg] )+ |Ensures that +obj1 == obj2+ is false.|
391
+ |+assert_same( obj1, obj2, [msg] )+ |Ensures that +obj1.equal?(obj2)+ is true.|
392
+ |+assert_not_same( obj1, obj2, [msg] )+ |Ensures that +obj1.equal?(obj2)+ is false.|
393
+ |+assert_nil( obj, [msg] )+ |Ensures that +obj.nil?+ is true.|
394
+ |+assert_not_nil( obj, [msg] )+ |Ensures that +obj.nil?+ is false.|
395
+ |+assert_match( regexp, string, [msg] )+ |Ensures that a string matches the regular expression.|
396
+ |+assert_no_match( regexp, string, [msg] )+ |Ensures that a string doesn't matches the regular expression.|
397
+ |+assert_in_delta( expecting, actual, delta, [msg] )+ |Ensures that the numbers +expecting+ and +actual+ are within +delta+ of each other.|
398
+ |+assert_throws( symbol, [msg] ) { block }+ |Ensures that the given block throws the symbol.|
399
+ |+assert_raise( exception1, exception2, ... ) { block }+ |Ensures that the given block raises one of the given exceptions.|
400
+ |+assert_nothing_raised( exception1, exception2, ... ) { block }+ |Ensures that the given block doesn't raise one of the given exceptions.|
401
+ |+assert_instance_of( class, obj, [msg] )+ |Ensures that +obj+ is of the +class+ type.|
402
+ |+assert_kind_of( class, obj, [msg] )+ |Ensures that +obj+ is or descends from +class+.|
403
+ |+assert_respond_to( obj, symbol, [msg] )+ |Ensures that +obj+ has a method called +symbol+.|
404
+ |+assert_operator( obj1, operator, obj2, [msg] )+ |Ensures that +obj1.operator(obj2)+ is true.|
405
+ |+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?|
406
+ |+flunk( [msg] )+ |Ensures failure. This is useful to explicitly mark a test that isn't finished yet.|
407
+
408
+ 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 includes some specialized assertions to make your life easier.
409
+
410
+ NOTE: Creating your own assertions is an advanced topic that we won't cover in this tutorial.
411
+
412
+ h4. Rails Specific Assertions
413
+
414
+ Rails adds some custom assertions of its own to the +test/unit+ framework:
415
+
416
+ |_.Assertion |_.Purpose|
417
+ |+assert_valid(record)+ |Ensures that the passed record is valid by Active Record standards and returns any error messages if it is not.|
418
+ |+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.|
419
+ |+assert_no_difference(expressions, message = nil, &block)+ |Asserts that the numeric result of evaluating an expression is not changed before and after invoking the passed in block.|
420
+ |+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.|
421
+ |+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.|
422
+ |+assert_response(type, message = nil)+ |Asserts that the response comes with a specific status code. You can specify +:success+ to indicate 200, +:redirect+ to indicate 300-399, +:missing+ to indicate 404, or +:error+ to match the 500-599 range|
423
+ |+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.|
424
+ |+assert_template(expected = nil, message=nil)+ |Asserts that the request was rendered with the appropriate template file.|
425
+
426
+ You'll see the usage of some of these assertions in the next chapter.
427
+
428
+ h3. Functional Tests for Your Controllers
429
+
430
+ In Rails, testing the various actions of a single controller is called writing functional tests for that controller. Controllers handle the incoming web requests to your application and eventually respond with a rendered view.
431
+
432
+ h4. What to Include in your Functional Tests
433
+
434
+ You should test for things such as:
435
+
436
+ * was the web request successful?
437
+ * was the user redirected to the right page?
438
+ * was the user successfully authenticated?
439
+ * was the correct object stored in the response template?
440
+ * was the appropriate message displayed to the user in the view
441
+
442
+ Now that we have used Rails scaffold generator for our +Post+ resource, it has already created the controller code and functional tests. You can take look at the file +posts_controller_test.rb+ in the +test/functional+ directory.
443
+
444
+ Let me take you through one such test, +test_should_get_index+ from the file +posts_controller_test.rb+.
445
+
446
+ <ruby>
447
+ def test_should_get_index
448
+ get :index
449
+ assert_response :success
450
+ assert_not_nil assigns(:posts)
451
+ end
452
+ </ruby>
453
+
454
+ In the +test_should_get_index+ test, Rails simulates a request on the action called index, making sure the request was successful and also ensuring that it assigns a valid +posts+ instance variable.
455
+
456
+ The +get+ method kicks off the web request and populates the results into the response. It accepts 4 arguments:
457
+
458
+ * The action of the controller you are requesting. This can be in the form of a string or a symbol.
459
+ * An optional hash of request parameters to pass into the action (eg. query string parameters or post variables).
460
+ * An optional hash of session variables to pass along with the request.
461
+ * An optional hash of flash values.
462
+
463
+ Example: Calling the +:show+ action, passing an +id+ of 12 as the +params+ and setting a +user_id+ of 5 in the session:
464
+
465
+ <ruby>
466
+ get(:show, {'id' => "12"}, {'user_id' => 5})
467
+ </ruby>
468
+
469
+ Another example: Calling the +:view+ action, passing an +id+ of 12 as the +params+, this time with no session, but with a flash message.
470
+
471
+ <ruby>
472
+ get(:view, {'id' => '12'}, nil, {'message' => 'booya!'})
473
+ </ruby>
474
+
475
+ NOTE: If you try running +test_should_create_post+ test from +posts_controller_test.rb+ it will fail on account of the newly added model level validation and rightly so.
476
+
477
+ Let us modify +test_should_create_post+ test in +posts_controller_test.rb+ so that all our test pass:
478
+
479
+ <ruby>
480
+ def test_should_create_post
481
+ assert_difference('Post.count') do
482
+ post :create, :post => { :title => 'Some title'}
483
+ end
484
+
485
+ assert_redirected_to post_path(assigns(:post))
486
+ end
487
+ </ruby>
488
+
489
+ Now you can try running all the tests and they should pass.
490
+
491
+ h4. Available Request Types for Functional Tests
492
+
493
+ If you're familiar with the HTTP protocol, you'll know that +get+ is a type of request. There are 5 request types supported in Rails functional tests:
494
+
495
+ * +get+
496
+ * +post+
497
+ * +put+
498
+ * +head+
499
+ * +delete+
500
+
501
+ 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.
502
+
503
+ h4. The Four Hashes of the Apocalypse
504
+
505
+ After a request has been made by using one of the 5 methods (+get+, +post+, etc.) and processed, you will have 4 Hash objects ready for use:
506
+
507
+ * +assigns+ - Any objects that are stored as instance variables in actions for use in views.
508
+ * +cookies+ - Any cookies that are set.
509
+ * +flash+ - Any objects living in the flash.
510
+ * +session+ - Any object living in session variables.
511
+
512
+ 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 for +assigns+. For example:
513
+
514
+ <ruby>
515
+ flash["gordon"] flash[:gordon]
516
+ session["shmession"] session[:shmession]
517
+ cookies["are_good_for_u"] cookies[:are_good_for_u]
518
+
519
+ # Because you can't use assigns[:something] for historical reasons:
520
+ assigns["something"] assigns(:something)
521
+ </ruby>
522
+
523
+ h4. Instance Variables Available
524
+
525
+ You also have access to three instance variables in your functional tests:
526
+
527
+ * +@controller+ - The controller processing the request
528
+ * +@request+ - The request
529
+ * +@response+ - The response
530
+
531
+ h4. A Fuller Functional Test Example
532
+
533
+ Here's another example that uses +flash+, +assert_redirected_to+, and +assert_difference+:
534
+
535
+ <ruby>
536
+ def test_should_create_post
537
+ assert_difference('Post.count') do
538
+ post :create, :post => { :title => 'Hi', :body => 'This is my first post.'}
539
+ end
540
+ assert_redirected_to post_path(assigns(:post))
541
+ assert_equal 'Post was successfully created.', flash[:notice]
542
+ end
543
+ </ruby>
544
+
545
+ h4. Testing Views
546
+
547
+ Testing the response to your request by asserting the presence of key HTML elements and their content is a useful way to test the views of your application. The +assert_select+ assertion allows you to do this by using a simple yet powerful syntax.
548
+
549
+ NOTE: You may find references to +assert_tag+ in other documentation, but this is now deprecated in favor of +assert_select+.
550
+
551
+ There are two forms of +assert_select+:
552
+
553
+ +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.
554
+
555
+ +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.
556
+
557
+ For example, you could verify the contents on the title element in your response with:
558
+
559
+ <ruby>
560
+ assert_select 'title', "Welcome to Rails Testing Guide"
561
+ </ruby>
562
+
563
+ You can also use nested +assert_select+ blocks. In this case the inner +assert_select+ runs the assertion on the complete collection of elements selected by the outer +assert_select+ block:
564
+
565
+ <ruby>
566
+ assert_select 'ul.navigation' do
567
+ assert_select 'li.menu_item'
568
+ end
569
+ </ruby>
570
+
571
+ Alternatively the collection of elements selected by the outer +assert_select+ may be iterated through so that +assert_select+ may be called separately for each element. Suppose for example that the response contains two ordered lists, each with four list elements then the following tests will both pass.
572
+
573
+ <ruby>
574
+ assert_select "ol" do |elements|
575
+ elements.each do |element|
576
+ assert_select element, "li", 4
577
+ end
578
+ end
579
+
580
+ assert_select "ol" do
581
+ assert_select "li", 8
582
+ end
583
+ </ruby>
584
+
585
+ The +assert_select+ assertion is quite powerful. For more advanced usage, refer to its "documentation":http://api.rubyonrails.org/classes/ActionController/Assertions/SelectorAssertions.html.
586
+
587
+ h5. Additional View-Based Assertions
588
+
589
+ There are more assertions that are primarily used in testing views:
590
+
591
+ |_.Assertion |_.Purpose|
592
+ |+assert_select_email+ |Allows you to make assertions on the body of an e-mail. |
593
+ |+assert_select_rjs+ |Allows you to make assertions on RJS response. +assert_select_rjs+ has variants which allow you to narrow down on the updated element or even a particular operation on an element.|
594
+ |+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.|
595
+ |+css_select(selector)+ or +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.|
596
+
597
+ Here's an example of using +assert_select_email+:
598
+
599
+ <ruby>
600
+ assert_select_email do
601
+ assert_select 'small', 'Please click the "Unsubscribe" link if you want to opt-out.'
602
+ end
603
+ </ruby>
604
+
605
+ h3. Integration Testing
606
+
607
+ Integration tests are used to test the interaction among any number of controllers. They are generally used to test important work flows within your application.
608
+
609
+ Unlike Unit and Functional tests, integration tests have to be explicitly created under the 'test/integration' folder within your application. Rails provides a generator to create an integration test skeleton for you.
610
+
611
+ <shell>
612
+ $ script/generate integration_test user_flows
613
+ exists test/integration/
614
+ create test/integration/user_flows_test.rb
615
+ </shell>
616
+
617
+ Here's what a freshly-generated integration test looks like:
618
+
619
+ <ruby>
620
+ require 'test_helper'
621
+
622
+ class UserFlowsTest < ActionController::IntegrationTest
623
+ # fixtures :your, :models
624
+
625
+ # Replace this with your real tests.
626
+ def test_truth
627
+ assert true
628
+ end
629
+ end
630
+ </ruby>
631
+
632
+ Integration tests inherit from +ActionController::IntegrationTest+. This makes available some additional helpers to use in your integration tests. Also you need to explicitly include the fixtures to be made available to the test.
633
+
634
+ h4. Helpers Available for Integration Tests
635
+
636
+ In addition to the standard testing helpers, there are some additional helpers available to integration tests:
637
+
638
+ |_.Helper |_.Purpose|
639
+ |+https?+ |Returns +true+ if the session is mimicking a secure HTTPS request.|
640
+ |+https!+ |Allows you to mimic a secure HTTPS request.|
641
+ |+host!+ |Allows you to set the host name to use in the next request.|
642
+ |+redirect?+ |Returns +true+ if the last request was a redirect.|
643
+ |+follow_redirect!+ |Follows a single redirect response.|
644
+ |+request_via_redirect(http_method, path, [parameters], [headers])+ |Allows you to make an HTTP request and follow any subsequent redirects.|
645
+ |+post_via_redirect(path, [parameters], [headers])+ |Allows you to make an HTTP POST request and follow any subsequent redirects.|
646
+ |+get_via_redirect(path, [parameters], [headers])+ |Allows you to make an HTTP GET request and follow any subsequent redirects.|
647
+ |+put_via_redirect(path, [parameters], [headers])+ |Allows you to make an HTTP PUT request and follow any subsequent redirects.|
648
+ |+delete_via_redirect(path, [parameters], [headers])+ |Allows you to make an HTTP DELETE request and follow any subsequent redirects.|
649
+ |+open_session+ |Opens a new session instance.|
650
+
651
+ h4. Integration Testing Examples
652
+
653
+ A simple integration test that exercises multiple controllers:
654
+
655
+ <ruby>
656
+ require 'test_helper'
657
+
658
+ class UserFlowsTest < ActionController::IntegrationTest
659
+ fixtures :users
660
+
661
+ def test_login_and_browse_site
662
+ # login via https
663
+ https!
664
+ get "/login"
665
+ assert_response :success
666
+
667
+ post_via_redirect "/login", :username => users(:avs).username, :password => users(:avs).password
668
+ assert_equal '/welcome', path
669
+ assert_equal 'Welcome avs!', flash[:notice]
670
+
671
+ https!(false)
672
+ get "/posts/all"
673
+ assert_response :success
674
+ assert assigns(:products)
675
+ end
676
+ end
677
+ </ruby>
678
+
679
+ As you can see the integration test involves multiple controllers and exercises the entire stack from database to dispatcher. In addition you can have multiple session instances open simultaneously in a test and extend those instances with assertion methods to create a very powerful testing DSL (domain-specific language) just for your application.
680
+
681
+ Here's an example of multiple sessions and custom DSL in an integration test
682
+
683
+ <ruby>
684
+ require 'test_helper'
685
+
686
+ class UserFlowsTest < ActionController::IntegrationTest
687
+ fixtures :users
688
+
689
+ def test_login_and_browse_site
690
+
691
+ # User avs logs in
692
+ avs = login(:avs)
693
+ # User guest logs in
694
+ guest = login(:guest)
695
+
696
+ # Both are now available in different sessions
697
+ assert_equal 'Welcome avs!', avs.flash[:notice]
698
+ assert_equal 'Welcome guest!', guest.flash[:notice]
699
+
700
+ # User avs can browse site
701
+ avs.browses_site
702
+ # User guest can browse site aswell
703
+ guest.browses_site
704
+
705
+ # Continue with other assertions
706
+ end
707
+
708
+ private
709
+
710
+ module CustomDsl
711
+ def browses_site
712
+ get "/products/all"
713
+ assert_response :success
714
+ assert assigns(:products)
715
+ end
716
+ end
717
+
718
+ def login(user)
719
+ open_session do |sess|
720
+ sess.extend(CustomDsl)
721
+ u = users(user)
722
+ sess.https!
723
+ sess.post "/login", :username => u.username, :password => u.password
724
+ assert_equal '/welcome', path
725
+ sess.https!(false)
726
+ end
727
+ end
728
+ end
729
+ </ruby>
730
+
731
+ h3. Rake Tasks for Running your Tests
732
+
733
+ You don't need to set up and run your tests by hand on a test-by-test basis. Rails comes with a number of rake tasks to help in testing. The table below lists all rake tasks that come along in the default Rakefile when you initiate a Rail project.
734
+
735
+ |_.Tasks |_.Description|
736
+ |+rake test+ |Runs all unit, functional and integration tests. You can also simply run +rake+ as the _test_ target is the default.|
737
+ |+rake test:units+ |Runs all the unit tests from +test/unit+|
738
+ |+rake test:functionals+ |Runs all the functional tests from +test/functional+|
739
+ |+rake test:integration+ |Runs all the integration tests from +test/integration+|
740
+ |+rake test:recent+ |Tests recent changes|
741
+ |+rake test:uncommitted+ |Runs all the tests which are uncommitted. Only supports Subversion|
742
+ |+rake test:plugins+ |Run all the plugin tests from +vendor/plugins/*/**/test+ (or specify with +PLUGIN=_name_+)|
743
+
744
+ h3. Brief Note About +Test::Unit+
745
+
746
+ Ruby ships with a boat load of libraries. One little gem of a library is +Test::Unit+, a framework for unit testing in Ruby. All the basic assertions discussed above are actually defined in +Test::Unit::Assertions+. The class +ActiveSupport::TestCase+ which we have been using in our unit and functional tests extends +Test::Unit::TestCase+ that it is how we can use all the basic assertions in our tests.
747
+
748
+ NOTE: For more information on +Test::Unit+, refer to "test/unit Documentation":http://ruby-doc.org/stdlib/libdoc/test/unit/rdoc/
749
+
750
+ h3. Setup and Teardown
751
+
752
+ If you would like to run a block of code before the start of each test and another block of code after the end of each test you have two special callbacks for your rescue. Let's take note of this by looking at an example for our functional test in +Posts+ controller:
753
+
754
+ <ruby>
755
+ require 'test_helper'
756
+
757
+ class PostsControllerTest < ActionController::TestCase
758
+
759
+ # called before every single test
760
+ def setup
761
+ @post = posts(:one)
762
+ end
763
+
764
+ # called after every single test
765
+ def teardown
766
+ # as we are re-initializing @post before every test
767
+ # setting it to nil here is not essential but I hope
768
+ # you understand how you can use the teardown method
769
+ @post = nil
770
+ end
771
+
772
+ def test_should_show_post
773
+ get :show, :id => @post.id
774
+ assert_response :success
775
+ end
776
+
777
+ def test_should_destroy_post
778
+ assert_difference('Post.count', -1) do
779
+ delete :destroy, :id => @post.id
780
+ end
781
+
782
+ assert_redirected_to posts_path
783
+ end
784
+
785
+ end
786
+ </ruby>
787
+
788
+ Above, the +setup+ method is called before each test and so +@post+ is available for each of the tests. Rails implements +setup+ and +teardown+ as ActiveSupport::Callbacks. Which essentially means you need not only use +setup+ and +teardown+ as methods in your tests. You could specify them by using:
789
+
790
+ * a block
791
+ * a method (like in the earlier example)
792
+ * a method name as a symbol
793
+ * a lambda
794
+
795
+ Let's see the earlier example by specifying +setup+ callback by specifying a method name as a symbol:
796
+
797
+ <ruby>
798
+ require '../test_helper'
799
+
800
+ class PostsControllerTest < ActionController::TestCase
801
+
802
+ # called before every single test
803
+ setup :initialize_post
804
+
805
+ # called after every single test
806
+ def teardown
807
+ @post = nil
808
+ end
809
+
810
+ def test_should_show_post
811
+ get :show, :id => @post.id
812
+ assert_response :success
813
+ end
814
+
815
+ def test_should_update_post
816
+ put :update, :id => @post.id, :post => { }
817
+ assert_redirected_to post_path(assigns(:post))
818
+ end
819
+
820
+ def test_should_destroy_post
821
+ assert_difference('Post.count', -1) do
822
+ delete :destroy, :id => @post.id
823
+ end
824
+
825
+ assert_redirected_to posts_path
826
+ end
827
+
828
+ private
829
+
830
+ def initialize_post
831
+ @post = posts(:one)
832
+ end
833
+
834
+ end
835
+ </ruby>
836
+
837
+ h3. Testing Routes
838
+
839
+ Like everything else in you Rails application, it's recommended to test you routes. An example test for a route in the default +show+ action of +Posts+ controller above should look like:
840
+
841
+ <ruby>
842
+ def test_should_route_to_post
843
+ assert_routing '/posts/1', { :controller => "posts", :action => "show", :id => "1" }
844
+ end
845
+ </ruby>
846
+
847
+ h3. Testing Your Mailers
848
+
849
+ Testing mailer classes requires some specific tools to do a thorough job.
850
+
851
+ h4. Keeping the Postman in Check
852
+
853
+ Your +ActionMailer+ classes -- like every other part of your Rails application -- should be tested to ensure that it is working as expected.
854
+
855
+ The goals of testing your +ActionMailer+ classes are to ensure that:
856
+
857
+ * emails are being processed (created and sent)
858
+ * the email content is correct (subject, sender, body, etc)
859
+ * the right emails are being sent at the right times
860
+
861
+ h5. From All Sides
862
+
863
+ There are two aspects of testing your mailer, the unit tests and the functional tests. In the unit tests, you run the mailer in isolation with tightly controlled inputs and compare the output to a knownvalue (a fixture -- yay! more fixtures!). In the functional tests you 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. You test to prove that the right email was sent at the right time.
864
+
865
+ h4. Unit Testing
866
+
867
+ In order to test that your mailer is working as expected, you can use unit tests to compare the actual results of the mailer with pre-written examples of what should be produced.
868
+
869
+ h5. Revenge of the Fixtures
870
+
871
+ For the purposes of unit testing a mailer, fixtures are used to provide an example of how the output _should_ look. Because these are example emails, and not Active Record data like the other fixtures, they are kept in their own subdirectory apart from the other fixtures. The name of the directory within +test/fixtures+ directly corresponds to the name of the mailer. So, for a mailer named +UserMailer+, the fixtures should reside in +test/fixtures/user_mailer+ directory.
872
+
873
+ When you generated your mailer, the generator creates stub fixtures for each of the mailers actions. If you didn't use the generator you'll have to make those files yourself.
874
+
875
+ h5. The Basic Test Case
876
+
877
+ Here's a unit test to test a mailer named +UserMailer+ whose action +invite+ is used to send an invitation to a friend. It is an adapted version of the base test created by the generator for an +invite+ action.
878
+
879
+ <ruby>
880
+ require 'test_helper'
881
+
882
+ class UserMailerTest < ActionMailer::TestCase
883
+ tests UserMailer
884
+ def test_invite
885
+ @expected.from = 'me@example.com'
886
+ @expected.to = 'friend@example.com'
887
+ @expected.subject = "You have been invited by #{@expected.from}"
888
+ @expected.body = read_fixture('invite')
889
+ @expected.date = Time.now
890
+
891
+ assert_equal @expected.encoded, UserMailer.create_invite('me@example.com', 'friend@example.com', @expected.date).encoded
892
+ end
893
+
894
+ end
895
+ </ruby>
896
+
897
+ In this test, +@expected+ is an instance of +TMail::Mail+ that you can use in your tests. It is defined in +ActionMailer::TestCase+. The test above uses +@expected+ to construct an email, which it then asserts with email created by the custom mailer. The +invite+ fixture is the body of the email and is used as the sample content to assert against. The helper +read_fixture+ is used to read in the content from this file.
898
+
899
+ Here's the content of the +invite+ fixture:
900
+
901
+ <pre>
902
+ Hi friend@example.com,
903
+
904
+ You have been invited.
905
+
906
+ Cheers!
907
+ </pre>
908
+
909
+ This is the right time to understand a little more about writing tests for your mailers. The line +ActionMailer::Base.delivery_method = :test+ in +config/environments/test.rb+ 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+).
910
+
911
+ 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.
912
+
913
+ h4. Functional Testing
914
+
915
+ Functional testing for mailers involves more than just checking that the email body, recipients and so forth are correct. In functional mail tests you 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 You are probably more interested in is whether your own business logic is sending emails when you expect them to got out. For example, you can check that the invite friend operation is sending an email appropriately:
916
+
917
+ <ruby>
918
+ require 'test_helper'
919
+
920
+ class UserControllerTest < ActionController::TestCase
921
+ def test_invite_friend
922
+ assert_difference 'ActionMailer::Base.deliveries.size', +1 do
923
+ post :invite_friend, :email => 'friend@example.com'
924
+ end
925
+ invite_email = ActionMailer::Base.deliveries.first
926
+
927
+ assert_equal invite_email.subject, "You have been invited by me@example.com"
928
+ assert_equal invite_email.to[0], 'friend@example.com'
929
+ assert_match /Hi friend@example.com/, invite_email.body
930
+ end
931
+ end
932
+ </ruby>
933
+
934
+ h3. Other Testing Approaches
935
+
936
+ The built-in +test/unit+ based testing is not the only way to test Rails applications. Rails developers have come up with a wide variety of other approaches and aids for testing, including:
937
+
938
+ * "NullDB":http://avdi.org/projects/nulldb/, a way to speed up testing by avoiding database use.
939
+ * "Factory Girl":http://github.com/thoughtbot/factory_girl/tree/master, as replacement for fixtures.
940
+ * "Machinist":http://github.com/notahat/machinist/tree/master, another replacement for fixtures.
941
+ * "Shoulda":http://www.thoughtbot.com/projects/shoulda, an extension to +test/unit+ with additional helpers, macros, and assertions.
942
+ * "RSpec":http://rspec.info/, a behavior-driven development framework
943
+
944
+ h3. Changelog
945
+
946
+ "Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/8
947
+
948
+ * November 13, 2008: Revised based on feedback from Pratik Naik by "Akshay Surve":credits.html#asurve (not yet approved for publication)
949
+ * October 14, 2008: Edit and formatting pass by "Mike Gunderloy":credits.html#mgunderloy (not yet approved for publication)
950
+ * October 12, 2008: First draft by "Akshay Surve":credits.html#asurve (not yet approved for publication)
951
+