rails 4.2.11 → 5.0.0

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