rails_test 4.2.0.beta1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (215) hide show
  1. checksums.yaml +7 -0
  2. data/README.md +83 -0
  3. data/guides/CHANGELOG.md +27 -0
  4. data/guides/Rakefile +77 -0
  5. data/guides/assets/images/akshaysurve.jpg +0 -0
  6. data/guides/assets/images/belongs_to.png +0 -0
  7. data/guides/assets/images/book_icon.gif +0 -0
  8. data/guides/assets/images/bullet.gif +0 -0
  9. data/guides/assets/images/chapters_icon.gif +0 -0
  10. data/guides/assets/images/check_bullet.gif +0 -0
  11. data/guides/assets/images/credits_pic_blank.gif +0 -0
  12. data/guides/assets/images/csrf.png +0 -0
  13. data/guides/assets/images/edge_badge.png +0 -0
  14. data/guides/assets/images/favicon.ico +0 -0
  15. data/guides/assets/images/feature_tile.gif +0 -0
  16. data/guides/assets/images/footer_tile.gif +0 -0
  17. data/guides/assets/images/fxn.png +0 -0
  18. data/guides/assets/images/getting_started/article_with_comments.png +0 -0
  19. data/guides/assets/images/getting_started/challenge.png +0 -0
  20. data/guides/assets/images/getting_started/confirm_dialog.png +0 -0
  21. data/guides/assets/images/getting_started/forbidden_attributes_for_new_article.png +0 -0
  22. data/guides/assets/images/getting_started/form_with_errors.png +0 -0
  23. data/guides/assets/images/getting_started/index_action_with_edit_link.png +0 -0
  24. data/guides/assets/images/getting_started/new_article.png +0 -0
  25. data/guides/assets/images/getting_started/rails_welcome.png +0 -0
  26. data/guides/assets/images/getting_started/routing_error_no_controller.png +0 -0
  27. data/guides/assets/images/getting_started/routing_error_no_route_matches.png +0 -0
  28. data/guides/assets/images/getting_started/show_action_for_articles.png +0 -0
  29. data/guides/assets/images/getting_started/template_is_missing_articles_new.png +0 -0
  30. data/guides/assets/images/getting_started/unknown_action_create_for_articles.png +0 -0
  31. data/guides/assets/images/getting_started/unknown_action_new_for_articles.png +0 -0
  32. data/guides/assets/images/grey_bullet.gif +0 -0
  33. data/guides/assets/images/habtm.png +0 -0
  34. data/guides/assets/images/has_many.png +0 -0
  35. data/guides/assets/images/has_many_through.png +0 -0
  36. data/guides/assets/images/has_one.png +0 -0
  37. data/guides/assets/images/has_one_through.png +0 -0
  38. data/guides/assets/images/header_backdrop.png +0 -0
  39. data/guides/assets/images/header_tile.gif +0 -0
  40. data/guides/assets/images/i18n/demo_html_safe.png +0 -0
  41. data/guides/assets/images/i18n/demo_localized_pirate.png +0 -0
  42. data/guides/assets/images/i18n/demo_translated_en.png +0 -0
  43. data/guides/assets/images/i18n/demo_translated_pirate.png +0 -0
  44. data/guides/assets/images/i18n/demo_translation_missing.png +0 -0
  45. data/guides/assets/images/i18n/demo_untranslated.png +0 -0
  46. data/guides/assets/images/icons/README +5 -0
  47. data/guides/assets/images/icons/callouts/1.png +0 -0
  48. data/guides/assets/images/icons/callouts/10.png +0 -0
  49. data/guides/assets/images/icons/callouts/11.png +0 -0
  50. data/guides/assets/images/icons/callouts/12.png +0 -0
  51. data/guides/assets/images/icons/callouts/13.png +0 -0
  52. data/guides/assets/images/icons/callouts/14.png +0 -0
  53. data/guides/assets/images/icons/callouts/15.png +0 -0
  54. data/guides/assets/images/icons/callouts/2.png +0 -0
  55. data/guides/assets/images/icons/callouts/3.png +0 -0
  56. data/guides/assets/images/icons/callouts/4.png +0 -0
  57. data/guides/assets/images/icons/callouts/5.png +0 -0
  58. data/guides/assets/images/icons/callouts/6.png +0 -0
  59. data/guides/assets/images/icons/callouts/7.png +0 -0
  60. data/guides/assets/images/icons/callouts/8.png +0 -0
  61. data/guides/assets/images/icons/callouts/9.png +0 -0
  62. data/guides/assets/images/icons/caution.png +0 -0
  63. data/guides/assets/images/icons/example.png +0 -0
  64. data/guides/assets/images/icons/home.png +0 -0
  65. data/guides/assets/images/icons/important.png +0 -0
  66. data/guides/assets/images/icons/next.png +0 -0
  67. data/guides/assets/images/icons/note.png +0 -0
  68. data/guides/assets/images/icons/prev.png +0 -0
  69. data/guides/assets/images/icons/tip.png +0 -0
  70. data/guides/assets/images/icons/up.png +0 -0
  71. data/guides/assets/images/icons/warning.png +0 -0
  72. data/guides/assets/images/nav_arrow.gif +0 -0
  73. data/guides/assets/images/oscardelben.jpg +0 -0
  74. data/guides/assets/images/polymorphic.png +0 -0
  75. data/guides/assets/images/radar.png +0 -0
  76. data/guides/assets/images/rails4_features.png +0 -0
  77. data/guides/assets/images/rails_guides_kindle_cover.jpg +0 -0
  78. data/guides/assets/images/rails_guides_logo.gif +0 -0
  79. data/guides/assets/images/rails_logo_remix.gif +0 -0
  80. data/guides/assets/images/session_fixation.png +0 -0
  81. data/guides/assets/images/tab_grey.gif +0 -0
  82. data/guides/assets/images/tab_info.gif +0 -0
  83. data/guides/assets/images/tab_note.gif +0 -0
  84. data/guides/assets/images/tab_red.gif +0 -0
  85. data/guides/assets/images/tab_yellow.gif +0 -0
  86. data/guides/assets/images/tab_yellow.png +0 -0
  87. data/guides/assets/images/vijaydev.jpg +0 -0
  88. data/guides/assets/javascripts/guides.js +59 -0
  89. data/guides/assets/javascripts/jquery.min.js +4 -0
  90. data/guides/assets/javascripts/responsive-tables.js +43 -0
  91. data/guides/assets/javascripts/syntaxhighlighter/shBrushAS3.js +59 -0
  92. data/guides/assets/javascripts/syntaxhighlighter/shBrushAppleScript.js +75 -0
  93. data/guides/assets/javascripts/syntaxhighlighter/shBrushBash.js +59 -0
  94. data/guides/assets/javascripts/syntaxhighlighter/shBrushCSharp.js +65 -0
  95. data/guides/assets/javascripts/syntaxhighlighter/shBrushColdFusion.js +100 -0
  96. data/guides/assets/javascripts/syntaxhighlighter/shBrushCpp.js +97 -0
  97. data/guides/assets/javascripts/syntaxhighlighter/shBrushCss.js +91 -0
  98. data/guides/assets/javascripts/syntaxhighlighter/shBrushDelphi.js +55 -0
  99. data/guides/assets/javascripts/syntaxhighlighter/shBrushDiff.js +41 -0
  100. data/guides/assets/javascripts/syntaxhighlighter/shBrushErlang.js +52 -0
  101. data/guides/assets/javascripts/syntaxhighlighter/shBrushGroovy.js +67 -0
  102. data/guides/assets/javascripts/syntaxhighlighter/shBrushJScript.js +52 -0
  103. data/guides/assets/javascripts/syntaxhighlighter/shBrushJava.js +57 -0
  104. data/guides/assets/javascripts/syntaxhighlighter/shBrushJavaFX.js +58 -0
  105. data/guides/assets/javascripts/syntaxhighlighter/shBrushPerl.js +72 -0
  106. data/guides/assets/javascripts/syntaxhighlighter/shBrushPhp.js +88 -0
  107. data/guides/assets/javascripts/syntaxhighlighter/shBrushPlain.js +33 -0
  108. data/guides/assets/javascripts/syntaxhighlighter/shBrushPowerShell.js +74 -0
  109. data/guides/assets/javascripts/syntaxhighlighter/shBrushPython.js +64 -0
  110. data/guides/assets/javascripts/syntaxhighlighter/shBrushRuby.js +55 -0
  111. data/guides/assets/javascripts/syntaxhighlighter/shBrushSass.js +94 -0
  112. data/guides/assets/javascripts/syntaxhighlighter/shBrushScala.js +51 -0
  113. data/guides/assets/javascripts/syntaxhighlighter/shBrushSql.js +66 -0
  114. data/guides/assets/javascripts/syntaxhighlighter/shBrushVb.js +56 -0
  115. data/guides/assets/javascripts/syntaxhighlighter/shBrushXml.js +69 -0
  116. data/guides/assets/javascripts/syntaxhighlighter/shCore.js +17 -0
  117. data/guides/assets/stylesheets/fixes.css +16 -0
  118. data/guides/assets/stylesheets/kindle.css +11 -0
  119. data/guides/assets/stylesheets/main.css +713 -0
  120. data/guides/assets/stylesheets/print.css +52 -0
  121. data/guides/assets/stylesheets/reset.css +43 -0
  122. data/guides/assets/stylesheets/responsive-tables.css +50 -0
  123. data/guides/assets/stylesheets/style.css +13 -0
  124. data/guides/assets/stylesheets/syntaxhighlighter/shCore.css +226 -0
  125. data/guides/assets/stylesheets/syntaxhighlighter/shCoreDefault.css +328 -0
  126. data/guides/assets/stylesheets/syntaxhighlighter/shCoreDjango.css +331 -0
  127. data/guides/assets/stylesheets/syntaxhighlighter/shCoreEclipse.css +339 -0
  128. data/guides/assets/stylesheets/syntaxhighlighter/shCoreEmacs.css +324 -0
  129. data/guides/assets/stylesheets/syntaxhighlighter/shCoreFadeToGrey.css +328 -0
  130. data/guides/assets/stylesheets/syntaxhighlighter/shCoreMDUltra.css +324 -0
  131. data/guides/assets/stylesheets/syntaxhighlighter/shCoreMidnight.css +324 -0
  132. data/guides/assets/stylesheets/syntaxhighlighter/shCoreRDark.css +324 -0
  133. data/guides/assets/stylesheets/syntaxhighlighter/shThemeDefault.css +117 -0
  134. data/guides/assets/stylesheets/syntaxhighlighter/shThemeDjango.css +120 -0
  135. data/guides/assets/stylesheets/syntaxhighlighter/shThemeEclipse.css +128 -0
  136. data/guides/assets/stylesheets/syntaxhighlighter/shThemeEmacs.css +113 -0
  137. data/guides/assets/stylesheets/syntaxhighlighter/shThemeFadeToGrey.css +117 -0
  138. data/guides/assets/stylesheets/syntaxhighlighter/shThemeMDUltra.css +113 -0
  139. data/guides/assets/stylesheets/syntaxhighlighter/shThemeMidnight.css +113 -0
  140. data/guides/assets/stylesheets/syntaxhighlighter/shThemeRDark.css +113 -0
  141. data/guides/assets/stylesheets/syntaxhighlighter/shThemeRailsGuides.css +116 -0
  142. data/guides/bug_report_templates/action_controller_gem.rb +47 -0
  143. data/guides/bug_report_templates/action_controller_master.rb +56 -0
  144. data/guides/bug_report_templates/active_record_gem.rb +40 -0
  145. data/guides/bug_report_templates/active_record_master.rb +51 -0
  146. data/guides/rails_guides.rb +63 -0
  147. data/guides/rails_guides/generator.rb +248 -0
  148. data/guides/rails_guides/helpers.rb +53 -0
  149. data/guides/rails_guides/indexer.rb +68 -0
  150. data/guides/rails_guides/kindle.rb +119 -0
  151. data/guides/rails_guides/levenshtein.rb +39 -0
  152. data/guides/rails_guides/markdown.rb +167 -0
  153. data/guides/rails_guides/markdown/renderer.rb +82 -0
  154. data/guides/source/2_2_release_notes.md +435 -0
  155. data/guides/source/2_3_release_notes.md +621 -0
  156. data/guides/source/3_0_release_notes.md +611 -0
  157. data/guides/source/3_1_release_notes.md +559 -0
  158. data/guides/source/3_2_release_notes.md +568 -0
  159. data/guides/source/4_0_release_notes.md +279 -0
  160. data/guides/source/4_1_release_notes.md +730 -0
  161. data/guides/source/4_2_release_notes.md +736 -0
  162. data/guides/source/_license.html.erb +2 -0
  163. data/guides/source/_welcome.html.erb +19 -0
  164. data/guides/source/action_controller_overview.md +1247 -0
  165. data/guides/source/action_mailer_basics.md +738 -0
  166. data/guides/source/action_view_overview.md +1621 -0
  167. data/guides/source/active_job_basics.md +285 -0
  168. data/guides/source/active_model_basics.md +223 -0
  169. data/guides/source/active_record_basics.md +374 -0
  170. data/guides/source/active_record_callbacks.md +413 -0
  171. data/guides/source/active_record_migrations.md +1016 -0
  172. data/guides/source/active_record_postgresql.md +438 -0
  173. data/guides/source/active_record_querying.md +1785 -0
  174. data/guides/source/active_record_validations.md +1169 -0
  175. data/guides/source/active_support_core_extensions.md +3924 -0
  176. data/guides/source/active_support_instrumentation.md +497 -0
  177. data/guides/source/api_documentation_guidelines.md +361 -0
  178. data/guides/source/asset_pipeline.md +1361 -0
  179. data/guides/source/association_basics.md +2238 -0
  180. data/guides/source/caching_with_rails.md +379 -0
  181. data/guides/source/command_line.md +634 -0
  182. data/guides/source/configuring.md +1019 -0
  183. data/guides/source/contributing_to_ruby_on_rails.md +607 -0
  184. data/guides/source/credits.html.erb +80 -0
  185. data/guides/source/debugging_rails_applications.md +861 -0
  186. data/guides/source/development_dependencies_install.md +289 -0
  187. data/guides/source/documents.yaml +197 -0
  188. data/guides/source/engines.md +1401 -0
  189. data/guides/source/form_helpers.md +1010 -0
  190. data/guides/source/generators.md +676 -0
  191. data/guides/source/getting_started.md +2085 -0
  192. data/guides/source/i18n.md +1073 -0
  193. data/guides/source/index.html.erb +28 -0
  194. data/guides/source/initialization.md +704 -0
  195. data/guides/source/kindle/copyright.html.erb +1 -0
  196. data/guides/source/kindle/layout.html.erb +27 -0
  197. data/guides/source/kindle/rails_guides.opf.erb +52 -0
  198. data/guides/source/kindle/toc.html.erb +24 -0
  199. data/guides/source/kindle/toc.ncx.erb +64 -0
  200. data/guides/source/kindle/welcome.html.erb +5 -0
  201. data/guides/source/layout.html.erb +143 -0
  202. data/guides/source/layouts_and_rendering.md +1227 -0
  203. data/guides/source/maintenance_policy.md +75 -0
  204. data/guides/source/nested_model_forms.md +228 -0
  205. data/guides/source/plugins.md +444 -0
  206. data/guides/source/rails_application_templates.md +266 -0
  207. data/guides/source/rails_on_rack.md +332 -0
  208. data/guides/source/routing.md +1141 -0
  209. data/guides/source/ruby_on_rails_guides_guidelines.md +126 -0
  210. data/guides/source/security.md +1024 -0
  211. data/guides/source/testing.md +1055 -0
  212. data/guides/source/upgrading_ruby_on_rails.md +1046 -0
  213. data/guides/source/working_with_javascript_in_rails.md +407 -0
  214. data/guides/w3c_validator.rb +97 -0
  215. metadata +404 -0
@@ -0,0 +1,1055 @@
1
+ A Guide to Testing Rails Applications
2
+ =====================================
3
+
4
+ This guide covers built-in mechanisms in Rails for testing your application.
5
+
6
+ After reading this guide, you will know:
7
+
8
+ * Rails testing terminology.
9
+ * How to write unit, functional, and integration tests for your application.
10
+ * Other popular testing approaches and plugins.
11
+
12
+ --------------------------------------------------------------------------------
13
+
14
+ Why Write Tests for your Rails Applications?
15
+ --------------------------------------------
16
+
17
+ Rails makes it super easy to write your tests. It starts by producing skeleton test code while you are creating your models and controllers.
18
+
19
+ By simply running your Rails tests you can ensure your code adheres to the desired functionality even after some major code refactoring.
20
+
21
+ Rails tests can also simulate browser requests and thus you can test your application's response without having to test it through your browser.
22
+
23
+ Introduction to Testing
24
+ -----------------------
25
+
26
+ 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.
27
+
28
+ ### The Test Environment
29
+
30
+ By default, every Rails application has three environments: development, test, and production. The database for each one of them is configured in `config/database.yml`.
31
+
32
+ A dedicated test database allows you to set up and interact with test data in isolation. Tests can mangle test data with confidence, that won't touch the data in the development or production databases.
33
+
34
+ ### Rails Sets up for Testing from the Word Go
35
+
36
+ Rails creates a `test` folder for you as soon as you create a Rails project using `rails new` _application_name_. If you list the contents of this folder then you shall see:
37
+
38
+ ```bash
39
+ $ ls -F test
40
+ controllers/ helpers/ mailers/ test_helper.rb
41
+ fixtures/ integration/ models/
42
+ ```
43
+
44
+ The `models` directory is meant to hold tests for your models, the `controllers` directory is meant to hold tests for your controllers and the `integration` directory is meant to hold tests that involve any number of controllers interacting.
45
+
46
+ Fixtures are a way of organizing test data; they reside in the `fixtures` folder.
47
+
48
+ The `test_helper.rb` file holds the default configuration for your tests.
49
+
50
+ ### The Low-Down on Fixtures
51
+
52
+ For good tests, you'll need to give some thought to setting up test data.
53
+ In Rails, you can handle this by defining and customizing fixtures.
54
+ You can find comprehensive documentation in the [fixture api documentation](http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html).
55
+
56
+ #### What Are Fixtures?
57
+
58
+ _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 written in YAML. There is one file per model.
59
+
60
+ You'll find fixtures under your `test/fixtures` directory. When you run `rails generate model` to create a new model fixture stubs will be automatically created and placed in this directory.
61
+
62
+ #### YAML
63
+
64
+ 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`).
65
+
66
+ Here's a sample YAML fixture file:
67
+
68
+ ```yaml
69
+ # lo & behold! I am a YAML comment!
70
+ david:
71
+ name: David Heinemeier Hansson
72
+ birthday: 1979-10-15
73
+ profession: Systems development
74
+
75
+ steve:
76
+ name: Steve Ross Kellock
77
+ birthday: 1974-09-27
78
+ profession: guy with keyboard
79
+ ```
80
+
81
+ Each fixture is given a name followed by an indented list of colon-separated key/value pairs. Records are typically separated by a blank space. You can place comments in a fixture file by using the # character in the first column. Keys which resemble YAML keywords such as 'yes' and 'no' are quoted so that the YAML Parser correctly interprets them.
82
+
83
+ If you are working with [associations](/association_basics.html), you can simply
84
+ define a reference node between two different fixtures. Here's an example with
85
+ a belongs_to/has_many association:
86
+
87
+ ```yaml
88
+ # In fixtures/categories.yml
89
+ about:
90
+ name: About
91
+
92
+ # In fixtures/articles.yml
93
+ one:
94
+ title: Welcome to Rails!
95
+ body: Hello world!
96
+ category: about
97
+ ```
98
+
99
+ Note: For associations to reference one another by name, you cannot specify the `id:`
100
+ attribute on the fixtures. Rails will auto assign a primary key to be consistent between
101
+ runs. If you manually specify an `id:` attribute, this behavior will not work. For more
102
+ information on this association behavior please read the
103
+ [fixture api documentation](http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html).
104
+
105
+ #### ERB'in It Up
106
+
107
+ ERB allows you to embed Ruby code within templates. The YAML fixture format is pre-processed with ERB when Rails loads fixtures. This allows you to use Ruby to help you generate some sample data. For example, the following code generates a thousand users:
108
+
109
+ ```erb
110
+ <% 1000.times do |n| %>
111
+ user_<%= n %>:
112
+ username: <%= "user#{n}" %>
113
+ email: <%= "user#{n}@example.com" %>
114
+ <% end %>
115
+ ```
116
+
117
+ #### Fixtures in Action
118
+
119
+ Rails by default automatically loads all fixtures from the `test/fixtures` folder for your models and controllers test. Loading involves three steps:
120
+
121
+ * Remove any existing data from the table corresponding to the fixture
122
+ * Load the fixture data into the table
123
+ * Dump the fixture data into a variable in case you want to access it directly
124
+
125
+ #### Fixtures are Active Record objects
126
+
127
+ Fixtures are instances of Active Record. As mentioned in point #3 above, you can access the object directly because it is automatically setup as a local variable of the test case. For example:
128
+
129
+ ```ruby
130
+ # this will return the User object for the fixture named david
131
+ users(:david)
132
+
133
+ # this will return the property for david called id
134
+ users(:david).id
135
+
136
+ # one can also access methods available on the User class
137
+ email(david.girlfriend.email, david.location_tonight)
138
+ ```
139
+
140
+ Unit Testing your Models
141
+ ------------------------
142
+
143
+ In Rails, models tests are what you write to test your models.
144
+
145
+ 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. We will be using examples from this generated code and will be supplementing it with additional examples where necessary.
146
+
147
+ NOTE: For more information on Rails _scaffolding_, refer to [Getting Started with Rails](getting_started.html)
148
+
149
+ When you use `rails generate scaffold`, for a resource among other things it creates a test stub in the `test/models` folder:
150
+
151
+ ```bash
152
+ $ bin/rails generate scaffold article title:string body:text
153
+ ...
154
+ create app/models/article.rb
155
+ create test/models/article_test.rb
156
+ create test/fixtures/articles.yml
157
+ ...
158
+ ```
159
+
160
+ The default test stub in `test/models/article_test.rb` looks like this:
161
+
162
+ ```ruby
163
+ require 'test_helper'
164
+
165
+ class ArticleTest < ActiveSupport::TestCase
166
+ # test "the truth" do
167
+ # assert true
168
+ # end
169
+ end
170
+ ```
171
+
172
+ A line by line examination of this file will help get you oriented to Rails testing code and terminology.
173
+
174
+ ```ruby
175
+ require 'test_helper'
176
+ ```
177
+
178
+ As you know by now, `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.
179
+
180
+ ```ruby
181
+ class ArticleTest < ActiveSupport::TestCase
182
+ ```
183
+
184
+ The `ArticleTest` class defines a _test case_ because it inherits from `ActiveSupport::TestCase`. `ArticleTest` thus has all the methods available from `ActiveSupport::TestCase`. You'll see those methods a little later in this guide.
185
+
186
+ Any method defined within a class inherited from `Minitest::Test`
187
+ (which is the superclass of `ActiveSupport::TestCase`) that begins with `test_` (case sensitive) is simply called a test. So, `test_password` and `test_valid_password` are legal test names and are run automatically when the test case is run.
188
+
189
+ Rails adds a `test` method that takes a test name and a block. It generates a normal `Minitest::Unit` test with method names prefixed with `test_`. So,
190
+
191
+ ```ruby
192
+ test "the truth" do
193
+ assert true
194
+ end
195
+ ```
196
+
197
+ acts as if you had written
198
+
199
+ ```ruby
200
+ def test_the_truth
201
+ assert true
202
+ end
203
+ ```
204
+
205
+ only the `test` macro allows a more readable test name. You can still use regular method definitions though.
206
+
207
+ NOTE: The method name is generated by replacing spaces with underscores. The result does not need to be a valid Ruby identifier though, the name may contain punctuation characters etc. That's because in Ruby technically any string may be a method name. Odd ones need `define_method` and `send` calls, but formally there's no restriction.
208
+
209
+ ```ruby
210
+ assert true
211
+ ```
212
+
213
+ 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:
214
+
215
+ * does this value = that value?
216
+ * is this object nil?
217
+ * does this line of code throw an exception?
218
+ * is the user's password greater than 5 characters?
219
+
220
+ Every test contains one or more assertions. Only when all the assertions are successful will the test pass.
221
+
222
+ ### Maintaining the test database schema
223
+
224
+ In order to run your tests, your test database will need to have the current structure. The test helper checks whether your test database has any pending migrations. If so, it will try to load your `db/schema.rb` or `db/structure.sql` into the test database. If migrations are still pending, an error will be raised.
225
+
226
+ ### Running Tests
227
+
228
+ Running a test is as simple as invoking the file containing the test cases through `rake test` command.
229
+
230
+ ```bash
231
+ $ bin/rake test test/models/article_test.rb
232
+ .
233
+
234
+ Finished tests in 0.009262s, 107.9680 tests/s, 107.9680 assertions/s.
235
+
236
+ 1 tests, 1 assertions, 0 failures, 0 errors, 0 skips
237
+ ```
238
+
239
+ You can also run a particular test method from the test case by running the test and providing the `test method name`.
240
+
241
+ ```bash
242
+ $ bin/rake test test/models/article_test.rb test_the_truth
243
+ .
244
+
245
+ Finished tests in 0.009064s, 110.3266 tests/s, 110.3266 assertions/s.
246
+
247
+ 1 tests, 1 assertions, 0 failures, 0 errors, 0 skips
248
+ ```
249
+
250
+ This will run all test methods from the test case. Note that `test_helper.rb` is in the `test` directory, hence this directory needs to be added to the load path using the `-I` switch.
251
+
252
+ 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.
253
+
254
+ To see how a test failure is reported, you can add a failing test to the `article_test.rb` test case.
255
+
256
+ ```ruby
257
+ test "should not save article without title" do
258
+ article = Article.new
259
+ assert_not article.save
260
+ end
261
+ ```
262
+
263
+ Let us run this newly added test.
264
+
265
+ ```bash
266
+ $ bin/rake test test/models/article_test.rb test_should_not_save_article_without_title
267
+ F
268
+
269
+ Finished tests in 0.044632s, 22.4054 tests/s, 22.4054 assertions/s.
270
+
271
+ 1) Failure:
272
+ test_should_not_save_article_without_title(ArticleTest) [test/models/article_test.rb:6]:
273
+ Failed assertion, no message given.
274
+
275
+ 1 tests, 1 assertions, 1 failures, 0 errors, 0 skips
276
+ ```
277
+
278
+ 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:
279
+
280
+ ```ruby
281
+ test "should not save article without title" do
282
+ article = Article.new
283
+ assert_not article.save, "Saved the article without a title"
284
+ end
285
+ ```
286
+
287
+ Running this test shows the friendlier assertion message:
288
+
289
+ ```bash
290
+ 1) Failure:
291
+ test_should_not_save_article_without_title(ArticleTest) [test/models/article_test.rb:6]:
292
+ Saved the article without a title
293
+ ```
294
+
295
+ Now to get this test to pass we can add a model level validation for the _title_ field.
296
+
297
+ ```ruby
298
+ class Article < ActiveRecord::Base
299
+ validates :title, presence: true
300
+ end
301
+ ```
302
+
303
+ Now the test should pass. Let us verify by running the test again:
304
+
305
+ ```bash
306
+ $ bin/rake test test/models/article_test.rb test_should_not_save_article_without_title
307
+ .
308
+
309
+ Finished tests in 0.047721s, 20.9551 tests/s, 20.9551 assertions/s.
310
+
311
+ 1 tests, 1 assertions, 0 failures, 0 errors, 0 skips
312
+ ```
313
+
314
+ 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).
315
+
316
+ 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).
317
+
318
+ To see how an error gets reported, here's a test containing an error:
319
+
320
+ ```ruby
321
+ test "should report error" do
322
+ # some_undefined_variable is not defined elsewhere in the test case
323
+ some_undefined_variable
324
+ assert true
325
+ end
326
+ ```
327
+
328
+ Now you can see even more output in the console from running the tests:
329
+
330
+ ```bash
331
+ $ bin/rake test test/models/article_test.rb test_should_report_error
332
+ E
333
+
334
+ Finished tests in 0.030974s, 32.2851 tests/s, 0.0000 assertions/s.
335
+
336
+ 1) Error:
337
+ test_should_report_error(ArticleTest):
338
+ NameError: undefined local variable or method `some_undefined_variable' for #<ArticleTest:0x007fe32e24afe0>
339
+ test/models/article_test.rb:10:in `block in <class:ArticleTest>'
340
+
341
+ 1 tests, 0 assertions, 0 failures, 1 errors, 0 skips
342
+ ```
343
+
344
+ Notice the 'E' in the output. It denotes a test with error.
345
+
346
+ NOTE: The execution of each test method stops as soon as any error or an assertion failure is encountered, and the test suite continues with the next method. All test methods are executed in alphabetical order.
347
+
348
+ When a test fails you are presented with the corresponding backtrace. By default
349
+ Rails filters that backtrace and will only print lines relevant to your
350
+ application. This eliminates the framework noise and helps to focus on your
351
+ code. However there are situations when you want to see the full
352
+ backtrace. simply set the `BACKTRACE` environment variable to enable this
353
+ behavior:
354
+
355
+ ```bash
356
+ $ BACKTRACE=1 bin/rake test test/models/article_test.rb
357
+ ```
358
+
359
+ ### What to Include in Your Unit Tests
360
+
361
+ 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.
362
+
363
+ ### Available Assertions
364
+
365
+ 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.
366
+
367
+ There are a bunch of different types of assertions you can use.
368
+ Here's an extract of the assertions you can use with [`Minitest`](https://github.com/seattlerb/minitest), the default 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.
369
+
370
+ | Assertion | Purpose |
371
+ | ---------------------------------------------------------------- | ------- |
372
+ | `assert( test, [msg] )` | Ensures that `test` is true.|
373
+ | `assert_not( test, [msg] )` | Ensures that `test` is false.|
374
+ | `assert_equal( expected, actual, [msg] )` | Ensures that `expected == actual` is true.|
375
+ | `assert_not_equal( expected, actual, [msg] )` | Ensures that `expected != actual` is true.|
376
+ | `assert_same( expected, actual, [msg] )` | Ensures that `expected.equal?(actual)` is true.|
377
+ | `assert_not_same( expected, actual, [msg] )` | Ensures that `expected.equal?(actual)` is false.|
378
+ | `assert_nil( obj, [msg] )` | Ensures that `obj.nil?` is true.|
379
+ | `assert_not_nil( obj, [msg] )` | Ensures that `obj.nil?` is false.|
380
+ | `assert_empty( obj, [msg] )` | Ensures that `obj` is `empty?`.|
381
+ | `assert_not_empty( obj, [msg] )` | Ensures that `obj` is not `empty?`.|
382
+ | `assert_match( regexp, string, [msg] )` | Ensures that a string matches the regular expression.|
383
+ | `assert_no_match( regexp, string, [msg] )` | Ensures that a string doesn't match the regular expression.|
384
+ | `assert_includes( collection, obj, [msg] )` | Ensures that `obj` is in `collection`.|
385
+ | `assert_not_includes( collection, obj, [msg] )` | Ensures that `obj` is not in `collection`.|
386
+ | `assert_in_delta( expecting, actual, [delta], [msg] )` | Ensures that the numbers `expected` and `actual` are within `delta` of each other.|
387
+ | `assert_not_in_delta( expecting, actual, [delta], [msg] )` | Ensures that the numbers `expected` and `actual` are not within `delta` of each other.|
388
+ | `assert_throws( symbol, [msg] ) { block }` | Ensures that the given block throws the symbol.|
389
+ | `assert_raises( exception1, exception2, ... ) { block }` | Ensures that the given block raises one of the given exceptions.|
390
+ | `assert_nothing_raised( exception1, exception2, ... ) { block }` | Ensures that the given block doesn't raise one of the given exceptions.|
391
+ | `assert_instance_of( class, obj, [msg] )` | Ensures that `obj` is an instance of `class`.|
392
+ | `assert_not_instance_of( class, obj, [msg] )` | Ensures that `obj` is not an instance of `class`.|
393
+ | `assert_kind_of( class, obj, [msg] )` | Ensures that `obj` is or descends from `class`.|
394
+ | `assert_not_kind_of( class, obj, [msg] )` | Ensures that `obj` is not an instance of `class` and is not descending from it.|
395
+ | `assert_respond_to( obj, symbol, [msg] )` | Ensures that `obj` responds to `symbol`.|
396
+ | `assert_not_respond_to( obj, symbol, [msg] )` | Ensures that `obj` does not respond to `symbol`.|
397
+ | `assert_operator( obj1, operator, [obj2], [msg] )` | Ensures that `obj1.operator(obj2)` is true.|
398
+ | `assert_not_operator( obj1, operator, [obj2], [msg] )` | Ensures that `obj1.operator(obj2)` is false.|
399
+ | `assert_predicate ( obj, predicate, [msg] )` | Ensures that `obj.predicate` is true, e.g. `assert_predicate str, :empty?`|
400
+ | `assert_not_predicate ( obj, predicate, [msg] )` | Ensures that `obj.predicate` is false, e.g. `assert_not_predicate str, :empty?`|
401
+ | `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?|
402
+ | `flunk( [msg] )` | Ensures failure. This is useful to explicitly mark a test that isn't finished yet.|
403
+
404
+ The above are subset of assertions that minitest supports. For an exhaustive & more up-to-date list, please check [Minitest API documentation](http://docs.seattlerb.org/minitest/), specifically [`Minitest::Assertions`](http://docs.seattlerb.org/minitest/Minitest/Assertions.html)
405
+
406
+ 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.
407
+
408
+ NOTE: Creating your own assertions is an advanced topic that we won't cover in this tutorial.
409
+
410
+ ### Rails Specific Assertions
411
+
412
+ Rails adds some custom assertions of its own to the `minitest` framework:
413
+
414
+ | Assertion | Purpose |
415
+ | --------------------------------------------------------------------------------- | ------- |
416
+ | `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.|
417
+ | `assert_no_difference(expressions, message = nil, &amp;block)` | Asserts that the numeric result of evaluating an expression is not changed before and after invoking the passed in block.|
418
+ | `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.|
419
+ | `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.|
420
+ | `assert_response(type, message = nil)` | Asserts that the response comes with a specific status code. You can specify `:success` to indicate 200-299, `:redirect` to indicate 300-399, `:missing` to indicate 404, or `:error` to match the 500-599 range. You can also pass an explicit status number or its symbolic equivalent. For more information, see [full list of status codes](http://rubydoc.info/github/rack/rack/master/Rack/Utils#HTTP_STATUS_CODES-constant) and how their [mapping](http://rubydoc.info/github/rack/rack/master/Rack/Utils#SYMBOL_TO_STATUS_CODE-constant) works.|
421
+ | `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. You can also pass named routes such as `assert_redirected_to root_path` and Active Record objects such as `assert_redirected_to @article`.|
422
+ | `assert_template(expected = nil, message=nil)` | Asserts that the request was rendered with the appropriate template file.|
423
+
424
+ You'll see the usage of some of these assertions in the next chapter.
425
+
426
+ Functional Tests for Your Controllers
427
+ -------------------------------------
428
+
429
+ 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.
430
+
431
+ ### What to Include in your Functional Tests
432
+
433
+ You should test for things such as:
434
+
435
+ * was the web request successful?
436
+ * was the user redirected to the right page?
437
+ * was the user successfully authenticated?
438
+ * was the correct object stored in the response template?
439
+ * was the appropriate message displayed to the user in the view?
440
+
441
+ Now that we have used Rails scaffold generator for our `Article` resource, it has already created the controller code and tests. You can take look at the file `articles_controller_test.rb` in the `test/controllers` directory.
442
+
443
+ Let me take you through one such test, `test_should_get_index` from the file `articles_controller_test.rb`.
444
+
445
+ ```ruby
446
+ class ArticlesControllerTest < ActionController::TestCase
447
+ test "should get index" do
448
+ get :index
449
+ assert_response :success
450
+ assert_not_nil assigns(:articles)
451
+ end
452
+ end
453
+ ```
454
+
455
+ 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 `articles` instance variable.
456
+
457
+ The `get` method kicks off the web request and populates the results into the response. It accepts 4 arguments:
458
+
459
+ * The action of the controller you are requesting. This can be in the form of a string or a symbol.
460
+ * An optional hash of request parameters to pass into the action (eg. query string parameters or article variables).
461
+ * An optional hash of session variables to pass along with the request.
462
+ * An optional hash of flash values.
463
+
464
+ Example: Calling the `:show` action, passing an `id` of 12 as the `params` and setting a `user_id` of 5 in the session:
465
+
466
+ ```ruby
467
+ get(:show, {'id' => "12"}, {'user_id' => 5})
468
+ ```
469
+
470
+ Another example: Calling the `:view` action, passing an `id` of 12 as the `params`, this time with no session, but with a flash message.
471
+
472
+ ```ruby
473
+ get(:view, {'id' => '12'}, nil, {'message' => 'booya!'})
474
+ ```
475
+
476
+ NOTE: If you try running `test_should_create_article` test from `articles_controller_test.rb` it will fail on account of the newly added model level validation and rightly so.
477
+
478
+ Let us modify `test_should_create_article` test in `articles_controller_test.rb` so that all our test pass:
479
+
480
+ ```ruby
481
+ test "should create article" do
482
+ assert_difference('Article.count') do
483
+ post :create, article: {title: 'Some title'}
484
+ end
485
+
486
+ assert_redirected_to article_path(assigns(:article))
487
+ end
488
+ ```
489
+
490
+ Now you can try running all the tests and they should pass.
491
+
492
+ ### Available Request Types for Functional Tests
493
+
494
+ If you're familiar with the HTTP protocol, you'll know that `get` is a type of request. There are 6 request types supported in Rails functional tests:
495
+
496
+ * `get`
497
+ * `post`
498
+ * `patch`
499
+ * `put`
500
+ * `head`
501
+ * `delete`
502
+
503
+ 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.
504
+
505
+ NOTE: Functional tests do not verify whether the specified request type should be accepted by the action. Request types in this context exist to make your tests more descriptive.
506
+
507
+ ### The Four Hashes of the Apocalypse
508
+
509
+ After a request has been made using one of the 6 methods (`get`, `post`, etc.) and processed, you will have 4 Hash objects ready for use:
510
+
511
+ * `assigns` - Any objects that are stored as instance variables in actions for use in views.
512
+ * `cookies` - Any cookies that are set.
513
+ * `flash` - Any objects living in the flash.
514
+ * `session` - Any object living in session variables.
515
+
516
+ 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:
517
+
518
+ ```ruby
519
+ flash["gordon"] flash[:gordon]
520
+ session["shmession"] session[:shmession]
521
+ cookies["are_good_for_u"] cookies[:are_good_for_u]
522
+
523
+ # Because you can't use assigns[:something] for historical reasons:
524
+ assigns["something"] assigns(:something)
525
+ ```
526
+
527
+ ### Instance Variables Available
528
+
529
+ You also have access to three instance variables in your functional tests:
530
+
531
+ * `@controller` - The controller processing the request
532
+ * `@request` - The request
533
+ * `@response` - The response
534
+
535
+ ### Setting Headers and CGI variables
536
+
537
+ [HTTP headers](http://tools.ietf.org/search/rfc2616#section-5.3)
538
+ and
539
+ [CGI variables](http://tools.ietf.org/search/rfc3875#section-4.1)
540
+ can be set directly on the `@request` instance variable:
541
+
542
+ ```ruby
543
+ # setting a HTTP Header
544
+ @request.headers["Accept"] = "text/plain, text/html"
545
+ get :index # simulate the request with custom header
546
+
547
+ # setting a CGI variable
548
+ @request.headers["HTTP_REFERER"] = "http://example.com/home"
549
+ post :create # simulate the request with custom env variable
550
+ ```
551
+
552
+ ### Testing Templates and Layouts
553
+
554
+ If you want to make sure that the response rendered the correct template and layout, you can use the `assert_template`
555
+ method:
556
+
557
+ ```ruby
558
+ test "index should render correct template and layout" do
559
+ get :index
560
+ assert_template :index
561
+ assert_template layout: "layouts/application"
562
+ end
563
+ ```
564
+
565
+ Note that you cannot test for template and layout at the same time, with one call to `assert_template` method.
566
+ Also, for the `layout` test, you can give a regular expression instead of a string, but using the string, makes
567
+ things clearer. On the other hand, you have to include the "layouts" directory name even if you save your layout
568
+ file in this standard layout directory. Hence,
569
+
570
+ ```ruby
571
+ assert_template layout: "application"
572
+ ```
573
+
574
+ will not work.
575
+
576
+ If your view renders any partial, when asserting for the layout, you have to assert for the partial at the same time.
577
+ Otherwise, assertion will fail.
578
+
579
+ Hence:
580
+
581
+ ```ruby
582
+ test "new should render correct layout" do
583
+ get :new
584
+ assert_template layout: "layouts/application", partial: "_form"
585
+ end
586
+ ```
587
+
588
+ is the correct way to assert for the layout when the view renders a partial with name `_form`. Omitting the `:partial` key in your `assert_template` call will complain.
589
+
590
+ ### A Fuller Functional Test Example
591
+
592
+ Here's another example that uses `flash`, `assert_redirected_to`, and `assert_difference`:
593
+
594
+ ```ruby
595
+ test "should create article" do
596
+ assert_difference('Article.count') do
597
+ post :create, article: {title: 'Hi', body: 'This is my first article.'}
598
+ end
599
+ assert_redirected_to article_path(assigns(:article))
600
+ assert_equal 'Article was successfully created.', flash[:notice]
601
+ end
602
+ ```
603
+
604
+ ### Testing Views
605
+
606
+ 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.
607
+
608
+ NOTE: You may find references to `assert_tag` in other documentation. This has been removed in 4.2. Use `assert_select` instead.
609
+
610
+ There are two forms of `assert_select`:
611
+
612
+ `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) or an expression with substitution values.
613
+
614
+ `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 `Nokogiri::XML::Node` or `Nokogiri::XML::NodeSet`) and its descendants.
615
+
616
+ For example, you could verify the contents on the title element in your response with:
617
+
618
+ ```ruby
619
+ assert_select 'title', "Welcome to Rails Testing Guide"
620
+ ```
621
+
622
+ 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:
623
+
624
+ ```ruby
625
+ assert_select 'ul.navigation' do
626
+ assert_select 'li.menu_item'
627
+ end
628
+ ```
629
+
630
+ 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.
631
+
632
+ ```ruby
633
+ assert_select "ol" do |elements|
634
+ elements.each do |element|
635
+ assert_select element, "li", 4
636
+ end
637
+ end
638
+
639
+ assert_select "ol" do
640
+ assert_select "li", 8
641
+ end
642
+ ```
643
+
644
+ The `assert_select` assertion is quite powerful. For more advanced usage, refer to its [documentation](https://github.com/rails/rails-dom-testing/blob/master/lib/rails/dom/testing/assertions/selector_assertions.rb).
645
+
646
+ #### Additional View-Based Assertions
647
+
648
+ There are more assertions that are primarily used in testing views:
649
+
650
+ | Assertion | Purpose |
651
+ | --------------------------------------------------------- | ------- |
652
+ | `assert_select_email` | Allows you to make assertions on the body of an e-mail. |
653
+ | `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.|
654
+ | `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.|
655
+
656
+ Here's an example of using `assert_select_email`:
657
+
658
+ ```ruby
659
+ assert_select_email do
660
+ assert_select 'small', 'Please click the "Unsubscribe" link if you want to opt-out.'
661
+ end
662
+ ```
663
+
664
+ Integration Testing
665
+ -------------------
666
+
667
+ 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.
668
+
669
+ 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.
670
+
671
+ ```bash
672
+ $ bin/rails generate integration_test user_flows
673
+ exists test/integration/
674
+ create test/integration/user_flows_test.rb
675
+ ```
676
+
677
+ Here's what a freshly-generated integration test looks like:
678
+
679
+ ```ruby
680
+ require 'test_helper'
681
+
682
+ class UserFlowsTest < ActionDispatch::IntegrationTest
683
+ # test "the truth" do
684
+ # assert true
685
+ # end
686
+ end
687
+ ```
688
+
689
+ Integration tests inherit from `ActionDispatch::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.
690
+
691
+ ### Helpers Available for Integration Tests
692
+
693
+ In addition to the standard testing helpers, there are some additional helpers available to integration tests:
694
+
695
+ | Helper | Purpose |
696
+ | ------------------------------------------------------------------ | ------- |
697
+ | `https?` | Returns `true` if the session is mimicking a secure HTTPS request.|
698
+ | `https!` | Allows you to mimic a secure HTTPS request.|
699
+ | `host!` | Allows you to set the host name to use in the next request.|
700
+ | `redirect?` | Returns `true` if the last request was a redirect.|
701
+ | `follow_redirect!` | Follows a single redirect response.|
702
+ | `request_via_redirect(http_method, path, [parameters], [headers])` | Allows you to make an HTTP request and follow any subsequent redirects.|
703
+ | `post_via_redirect(path, [parameters], [headers])` | Allows you to make an HTTP POST request and follow any subsequent redirects.|
704
+ | `get_via_redirect(path, [parameters], [headers])` | Allows you to make an HTTP GET request and follow any subsequent redirects.|
705
+ | `patch_via_redirect(path, [parameters], [headers])` | Allows you to make an HTTP PATCH request and follow any subsequent redirects.|
706
+ | `put_via_redirect(path, [parameters], [headers])` | Allows you to make an HTTP PUT request and follow any subsequent redirects.|
707
+ | `delete_via_redirect(path, [parameters], [headers])` | Allows you to make an HTTP DELETE request and follow any subsequent redirects.|
708
+ | `open_session` | Opens a new session instance.|
709
+
710
+ ### Integration Testing Examples
711
+
712
+ A simple integration test that exercises multiple controllers:
713
+
714
+ ```ruby
715
+ require 'test_helper'
716
+
717
+ class UserFlowsTest < ActionDispatch::IntegrationTest
718
+ test "login and browse site" do
719
+ # login via https
720
+ https!
721
+ get "/login"
722
+ assert_response :success
723
+
724
+ post_via_redirect "/login", username: users(:david).username, password: users(:david).password
725
+ assert_equal '/welcome', path
726
+ assert_equal 'Welcome david!', flash[:notice]
727
+
728
+ https!(false)
729
+ get "/articles/all"
730
+ assert_response :success
731
+ assert assigns(:products)
732
+ end
733
+ end
734
+ ```
735
+
736
+ 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.
737
+
738
+ Here's an example of multiple sessions and custom DSL in an integration test
739
+
740
+ ```ruby
741
+ require 'test_helper'
742
+
743
+ class UserFlowsTest < ActionDispatch::IntegrationTest
744
+ test "login and browse site" do
745
+ # User david logs in
746
+ david = login(:david)
747
+ # User guest logs in
748
+ guest = login(:guest)
749
+
750
+ # Both are now available in different sessions
751
+ assert_equal 'Welcome david!', david.flash[:notice]
752
+ assert_equal 'Welcome guest!', guest.flash[:notice]
753
+
754
+ # User david can browse site
755
+ david.browses_site
756
+ # User guest can browse site as well
757
+ guest.browses_site
758
+
759
+ # Continue with other assertions
760
+ end
761
+
762
+ private
763
+
764
+ module CustomDsl
765
+ def browses_site
766
+ get "/products/all"
767
+ assert_response :success
768
+ assert assigns(:products)
769
+ end
770
+ end
771
+
772
+ def login(user)
773
+ open_session do |sess|
774
+ sess.extend(CustomDsl)
775
+ u = users(user)
776
+ sess.https!
777
+ sess.post "/login", username: u.username, password: u.password
778
+ assert_equal '/welcome', sess.path
779
+ sess.https!(false)
780
+ end
781
+ end
782
+ end
783
+ ```
784
+
785
+ Rake Tasks for Running your Tests
786
+ ---------------------------------
787
+
788
+ You don't need to set up and run your tests by hand on a test-by-test basis.
789
+ Rails comes with a number of commands to help in testing.
790
+ The table below lists all commands that come along in the default Rakefile
791
+ when you initiate a Rails project.
792
+
793
+ | Tasks | Description |
794
+ | ----------------------- | ----------- |
795
+ | `rake test` | Runs all unit, functional and integration tests. You can also simply run `rake` as Rails will run all the tests by default |
796
+ | `rake test:controllers` | Runs all the controller tests from `test/controllers` |
797
+ | `rake test:functionals` | Runs all the functional tests from `test/controllers`, `test/mailers`, and `test/functional` |
798
+ | `rake test:helpers` | Runs all the helper tests from `test/helpers` |
799
+ | `rake test:integration` | Runs all the integration tests from `test/integration` |
800
+ | `rake test:mailers` | Runs all the mailer tests from `test/mailers` |
801
+ | `rake test:models` | Runs all the model tests from `test/models` |
802
+ | `rake test:units` | Runs all the unit tests from `test/models`, `test/helpers`, and `test/unit` |
803
+ | `rake test:all` | Runs all tests quickly by merging all types and not resetting db |
804
+ | `rake test:all:db` | Runs all tests quickly by merging all types and resetting db |
805
+
806
+
807
+ Brief Note About `Minitest`
808
+ -----------------------------
809
+
810
+ Ruby ships with a vast Standard Library for all common use-cases including testing. Since version 1.9, Ruby provides `Minitest`, a framework for testing. All the basic assertions such as `assert_equal` discussed above are actually defined in `Minitest::Assertions`. The classes `ActiveSupport::TestCase`, `ActionController::TestCase`, `ActionMailer::TestCase`, `ActionView::TestCase` and `ActionDispatch::IntegrationTest` - which we have been inheriting in our test classes - include `Minitest::Assertions`, allowing us to use all of the basic assertions in our tests.
811
+
812
+ NOTE: For more information on `Minitest`, refer to [Minitest](http://ruby-doc.org/stdlib-2.1.0/libdoc/minitest/rdoc/MiniTest.html)
813
+
814
+ Setup and Teardown
815
+ ------------------
816
+
817
+ 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 `Articles` controller:
818
+
819
+ ```ruby
820
+ require 'test_helper'
821
+
822
+ class ArticlesControllerTest < ActionController::TestCase
823
+
824
+ # called before every single test
825
+ def setup
826
+ @article = articles(:one)
827
+ end
828
+
829
+ # called after every single test
830
+ def teardown
831
+ # as we are re-initializing @article before every test
832
+ # setting it to nil here is not essential but I hope
833
+ # you understand how you can use the teardown method
834
+ @article = nil
835
+ end
836
+
837
+ test "should show article" do
838
+ get :show, id: @article.id
839
+ assert_response :success
840
+ end
841
+
842
+ test "should destroy article" do
843
+ assert_difference('Article.count', -1) do
844
+ delete :destroy, id: @article.id
845
+ end
846
+
847
+ assert_redirected_to articles_path
848
+ end
849
+
850
+ end
851
+ ```
852
+
853
+ Above, the `setup` method is called before each test and so `@article` 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:
854
+
855
+ * a block
856
+ * a method (like in the earlier example)
857
+ * a method name as a symbol
858
+ * a lambda
859
+
860
+ Let's see the earlier example by specifying `setup` callback by specifying a method name as a symbol:
861
+
862
+ ```ruby
863
+ require 'test_helper'
864
+
865
+ class ArticlesControllerTest < ActionController::TestCase
866
+
867
+ # called before every single test
868
+ setup :initialize_article
869
+
870
+ # called after every single test
871
+ def teardown
872
+ @article = nil
873
+ end
874
+
875
+ test "should show article" do
876
+ get :show, id: @article.id
877
+ assert_response :success
878
+ end
879
+
880
+ test "should update article" do
881
+ patch :update, id: @article.id, article: {}
882
+ assert_redirected_to article_path(assigns(:article))
883
+ end
884
+
885
+ test "should destroy article" do
886
+ assert_difference('Article.count', -1) do
887
+ delete :destroy, id: @article.id
888
+ end
889
+
890
+ assert_redirected_to articles_path
891
+ end
892
+
893
+ private
894
+
895
+ def initialize_article
896
+ @article = articles(:one)
897
+ end
898
+ end
899
+ ```
900
+
901
+ Testing Routes
902
+ --------------
903
+
904
+ Like everything else in your Rails application, it is recommended that you test your routes. An example test for a route in the default `show` action of `Articles` controller above should look like:
905
+
906
+ ```ruby
907
+ test "should route to article" do
908
+ assert_routing '/articles/1', {controller: "articles", action: "show", id: "1"}
909
+ end
910
+ ```
911
+
912
+ Testing Your Mailers
913
+ --------------------
914
+
915
+ Testing mailer classes requires some specific tools to do a thorough job.
916
+
917
+ ### Keeping the Postman in Check
918
+
919
+ Your mailer classes - like every other part of your Rails application - should be tested to ensure that it is working as expected.
920
+
921
+ The goals of testing your mailer classes are to ensure that:
922
+
923
+ * emails are being processed (created and sent)
924
+ * the email content is correct (subject, sender, body, etc)
925
+ * the right emails are being sent at the right times
926
+
927
+ #### From All Sides
928
+
929
+ 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 known value (a fixture.) 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.
930
+
931
+ ### Unit Testing
932
+
933
+ 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.
934
+
935
+ #### Revenge of the Fixtures
936
+
937
+ 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.
938
+
939
+ 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.
940
+
941
+ #### The Basic Test Case
942
+
943
+ 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.
944
+
945
+ ```ruby
946
+ require 'test_helper'
947
+
948
+ class UserMailerTest < ActionMailer::TestCase
949
+ test "invite" do
950
+ # Send the email, then test that it got queued
951
+ email = UserMailer.create_invite('me@example.com',
952
+ 'friend@example.com', Time.now).deliver_now
953
+ assert_not ActionMailer::Base.deliveries.empty?
954
+
955
+ # Test the body of the sent email contains what we expect it to
956
+ assert_equal ['me@example.com'], email.from
957
+ assert_equal ['friend@example.com'], email.to
958
+ assert_equal 'You have been invited by me@example.com', email.subject
959
+ assert_equal read_fixture('invite').join, email.body.to_s
960
+ end
961
+ end
962
+ ```
963
+
964
+ In the test we send the email and store the returned object in the `email`
965
+ variable. We then ensure that it was sent (the first assert), then, in the
966
+ second batch of assertions, we ensure that the email does indeed contain what we
967
+ expect. The helper `read_fixture` is used to read in the content from this file.
968
+
969
+ Here's the content of the `invite` fixture:
970
+
971
+ ```
972
+ Hi friend@example.com,
973
+
974
+ You have been invited.
975
+
976
+ Cheers!
977
+ ```
978
+
979
+ This is the right time to understand a little more about writing tests for your
980
+ mailers. The line `ActionMailer::Base.delivery_method = :test` in
981
+ `config/environments/test.rb` sets the delivery method to test mode so that
982
+ email will not actually be delivered (useful to avoid spamming your users while
983
+ testing) but instead it will be appended to an array
984
+ (`ActionMailer::Base.deliveries`).
985
+
986
+ NOTE: The `ActionMailer::Base.deliveries` array is only reset automatically in
987
+ `ActionMailer::TestCase` tests. If you want to have a clean slate outside Action
988
+ Mailer tests, you can reset it manually with:
989
+ `ActionMailer::Base.deliveries.clear`
990
+
991
+ ### Functional Testing
992
+
993
+ 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 whether your own business logic is sending emails when you expect them to go out. For example, you can check that the invite friend operation is sending an email appropriately:
994
+
995
+ ```ruby
996
+ require 'test_helper'
997
+
998
+ class UserControllerTest < ActionController::TestCase
999
+ test "invite friend" do
1000
+ assert_difference 'ActionMailer::Base.deliveries.size', +1 do
1001
+ post :invite_friend, email: 'friend@example.com'
1002
+ end
1003
+ invite_email = ActionMailer::Base.deliveries.last
1004
+
1005
+ assert_equal "You have been invited by me@example.com", invite_email.subject
1006
+ assert_equal 'friend@example.com', invite_email.to[0]
1007
+ assert_match(/Hi friend@example.com/, invite_email.body.to_s)
1008
+ end
1009
+ end
1010
+ ```
1011
+
1012
+ Testing helpers
1013
+ ---------------
1014
+
1015
+ In order to test helpers, all you need to do is check that the output of the
1016
+ helper method matches what you'd expect. Tests related to the helpers are
1017
+ located under the `test/helpers` directory.
1018
+
1019
+ A helper test looks like so:
1020
+
1021
+ ```ruby
1022
+ require 'test_helper'
1023
+
1024
+ class UserHelperTest < ActionView::TestCase
1025
+ end
1026
+ ```
1027
+
1028
+ A helper is just a simple module where you can define methods which are
1029
+ available into your views. To test the output of the helper's methods, you just
1030
+ have to use a mixin like this:
1031
+
1032
+ ```ruby
1033
+ class UserHelperTest < ActionView::TestCase
1034
+ include UserHelper
1035
+
1036
+ test "should return the user name" do
1037
+ # ...
1038
+ end
1039
+ end
1040
+ ```
1041
+
1042
+ Moreover, since the test class extends from `ActionView::TestCase`, you have
1043
+ access to Rails' helper methods such as `link_to` or `pluralize`.
1044
+
1045
+ Other Testing Approaches
1046
+ ------------------------
1047
+
1048
+ The built-in `minitest` 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:
1049
+
1050
+ * [NullDB](http://avdi.org/projects/nulldb/), a way to speed up testing by avoiding database use.
1051
+ * [Factory Girl](https://github.com/thoughtbot/factory_girl/tree/master), a replacement for fixtures.
1052
+ * [Fixture Builder](https://github.com/rdy/fixture_builder), a tool that compiles Ruby factories into fixtures before a test run.
1053
+ * [MiniTest::Spec Rails](https://github.com/metaskills/minitest-spec-rails), use the MiniTest::Spec DSL within your rails tests.
1054
+ * [Shoulda](http://www.thoughtbot.com/projects/shoulda), an extension to `test/unit` with additional helpers, macros, and assertions.
1055
+ * [RSpec](http://relishapp.com/rspec), a behavior-driven development framework