rails 3.2.22.5 → 4.0.0.beta1

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

Potentially problematic release.


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

Files changed (281) hide show
  1. checksums.yaml +4 -4
  2. data/README.rdoc +77 -0
  3. data/guides/CHANGELOG.md +9 -0
  4. data/guides/Rakefile +77 -0
  5. data/guides/assets/images/belongs_to.png +0 -0
  6. data/guides/assets/images/book_icon.gif +0 -0
  7. data/guides/assets/images/bullet.gif +0 -0
  8. data/guides/assets/images/challenge.png +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/confirm_dialog.png +0 -0
  19. data/guides/assets/images/getting_started/forbidden_attributes_for_new_post.png +0 -0
  20. data/guides/assets/images/getting_started/form_with_errors.png +0 -0
  21. data/guides/assets/images/getting_started/index_action_with_edit_link.png +0 -0
  22. data/guides/assets/images/getting_started/new_post.png +0 -0
  23. data/guides/assets/images/getting_started/post_with_comments.png +0 -0
  24. data/guides/assets/images/getting_started/routing_error_no_controller.png +0 -0
  25. data/guides/assets/images/getting_started/routing_error_no_route_matches.png +0 -0
  26. data/guides/assets/images/getting_started/show_action_for_posts.png +0 -0
  27. data/guides/assets/images/getting_started/template_is_missing_posts_new.png +0 -0
  28. data/guides/assets/images/getting_started/undefined_method_post_path.png +0 -0
  29. data/guides/assets/images/getting_started/unknown_action_create_for_posts.png +0 -0
  30. data/guides/assets/images/getting_started/unknown_action_new_for_posts.png +0 -0
  31. data/guides/assets/images/grey_bullet.gif +0 -0
  32. data/guides/assets/images/habtm.png +0 -0
  33. data/guides/assets/images/has_many.png +0 -0
  34. data/guides/assets/images/has_many_through.png +0 -0
  35. data/guides/assets/images/has_one.png +0 -0
  36. data/guides/assets/images/has_one_through.png +0 -0
  37. data/guides/assets/images/header_backdrop.png +0 -0
  38. data/guides/assets/images/header_tile.gif +0 -0
  39. data/guides/assets/images/i18n/demo_html_safe.png +0 -0
  40. data/guides/assets/images/i18n/demo_localized_pirate.png +0 -0
  41. data/guides/assets/images/i18n/demo_translated_en.png +0 -0
  42. data/guides/assets/images/i18n/demo_translated_pirate.png +0 -0
  43. data/guides/assets/images/i18n/demo_translation_missing.png +0 -0
  44. data/guides/assets/images/i18n/demo_untranslated.png +0 -0
  45. data/guides/assets/images/icons/README +5 -0
  46. data/guides/assets/images/icons/callouts/1.png +0 -0
  47. data/guides/assets/images/icons/callouts/10.png +0 -0
  48. data/guides/assets/images/icons/callouts/11.png +0 -0
  49. data/guides/assets/images/icons/callouts/12.png +0 -0
  50. data/guides/assets/images/icons/callouts/13.png +0 -0
  51. data/guides/assets/images/icons/callouts/14.png +0 -0
  52. data/guides/assets/images/icons/callouts/15.png +0 -0
  53. data/guides/assets/images/icons/callouts/2.png +0 -0
  54. data/guides/assets/images/icons/callouts/3.png +0 -0
  55. data/guides/assets/images/icons/callouts/4.png +0 -0
  56. data/guides/assets/images/icons/callouts/5.png +0 -0
  57. data/guides/assets/images/icons/callouts/6.png +0 -0
  58. data/guides/assets/images/icons/callouts/7.png +0 -0
  59. data/guides/assets/images/icons/callouts/8.png +0 -0
  60. data/guides/assets/images/icons/callouts/9.png +0 -0
  61. data/guides/assets/images/icons/caution.png +0 -0
  62. data/guides/assets/images/icons/example.png +0 -0
  63. data/guides/assets/images/icons/home.png +0 -0
  64. data/guides/assets/images/icons/important.png +0 -0
  65. data/guides/assets/images/icons/next.png +0 -0
  66. data/guides/assets/images/icons/note.png +0 -0
  67. data/guides/assets/images/icons/prev.png +0 -0
  68. data/guides/assets/images/icons/tip.png +0 -0
  69. data/guides/assets/images/icons/up.png +0 -0
  70. data/guides/assets/images/icons/warning.png +0 -0
  71. data/guides/assets/images/jaimeiniesta.jpg +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/rails_welcome.png +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 +57 -0
  90. data/guides/assets/javascripts/jquery.min.js +4 -0
  91. data/guides/assets/javascripts/responsive-tables.js +43 -0
  92. data/guides/assets/javascripts/syntaxhighlighter/shBrushAS3.js +59 -0
  93. data/guides/assets/javascripts/syntaxhighlighter/shBrushAppleScript.js +75 -0
  94. data/guides/assets/javascripts/syntaxhighlighter/shBrushBash.js +59 -0
  95. data/guides/assets/javascripts/syntaxhighlighter/shBrushCSharp.js +65 -0
  96. data/guides/assets/javascripts/syntaxhighlighter/shBrushColdFusion.js +100 -0
  97. data/guides/assets/javascripts/syntaxhighlighter/shBrushCpp.js +97 -0
  98. data/guides/assets/javascripts/syntaxhighlighter/shBrushCss.js +91 -0
  99. data/guides/assets/javascripts/syntaxhighlighter/shBrushDelphi.js +55 -0
  100. data/guides/assets/javascripts/syntaxhighlighter/shBrushDiff.js +41 -0
  101. data/guides/assets/javascripts/syntaxhighlighter/shBrushErlang.js +52 -0
  102. data/guides/assets/javascripts/syntaxhighlighter/shBrushGroovy.js +67 -0
  103. data/guides/assets/javascripts/syntaxhighlighter/shBrushJScript.js +52 -0
  104. data/guides/assets/javascripts/syntaxhighlighter/shBrushJava.js +57 -0
  105. data/guides/assets/javascripts/syntaxhighlighter/shBrushJavaFX.js +58 -0
  106. data/guides/assets/javascripts/syntaxhighlighter/shBrushPerl.js +72 -0
  107. data/guides/assets/javascripts/syntaxhighlighter/shBrushPhp.js +88 -0
  108. data/guides/assets/javascripts/syntaxhighlighter/shBrushPlain.js +33 -0
  109. data/guides/assets/javascripts/syntaxhighlighter/shBrushPowerShell.js +74 -0
  110. data/guides/assets/javascripts/syntaxhighlighter/shBrushPython.js +64 -0
  111. data/guides/assets/javascripts/syntaxhighlighter/shBrushRuby.js +55 -0
  112. data/guides/assets/javascripts/syntaxhighlighter/shBrushSass.js +94 -0
  113. data/guides/assets/javascripts/syntaxhighlighter/shBrushScala.js +51 -0
  114. data/guides/assets/javascripts/syntaxhighlighter/shBrushSql.js +66 -0
  115. data/guides/assets/javascripts/syntaxhighlighter/shBrushVb.js +56 -0
  116. data/guides/assets/javascripts/syntaxhighlighter/shBrushXml.js +69 -0
  117. data/guides/assets/javascripts/syntaxhighlighter/shCore.js +17 -0
  118. data/guides/assets/stylesheets/fixes.css +16 -0
  119. data/guides/assets/stylesheets/kindle.css +11 -0
  120. data/guides/assets/stylesheets/main.css +709 -0
  121. data/guides/assets/stylesheets/print.css +52 -0
  122. data/guides/assets/stylesheets/reset.css +43 -0
  123. data/guides/assets/stylesheets/responsive-tables.css +50 -0
  124. data/guides/assets/stylesheets/style.css +13 -0
  125. data/guides/assets/stylesheets/syntaxhighlighter/shCore.css +226 -0
  126. data/guides/assets/stylesheets/syntaxhighlighter/shCoreDefault.css +328 -0
  127. data/guides/assets/stylesheets/syntaxhighlighter/shCoreDjango.css +331 -0
  128. data/guides/assets/stylesheets/syntaxhighlighter/shCoreEclipse.css +339 -0
  129. data/guides/assets/stylesheets/syntaxhighlighter/shCoreEmacs.css +324 -0
  130. data/guides/assets/stylesheets/syntaxhighlighter/shCoreFadeToGrey.css +328 -0
  131. data/guides/assets/stylesheets/syntaxhighlighter/shCoreMDUltra.css +324 -0
  132. data/guides/assets/stylesheets/syntaxhighlighter/shCoreMidnight.css +324 -0
  133. data/guides/assets/stylesheets/syntaxhighlighter/shCoreRDark.css +324 -0
  134. data/guides/assets/stylesheets/syntaxhighlighter/shThemeDefault.css +117 -0
  135. data/guides/assets/stylesheets/syntaxhighlighter/shThemeDjango.css +120 -0
  136. data/guides/assets/stylesheets/syntaxhighlighter/shThemeEclipse.css +128 -0
  137. data/guides/assets/stylesheets/syntaxhighlighter/shThemeEmacs.css +113 -0
  138. data/guides/assets/stylesheets/syntaxhighlighter/shThemeFadeToGrey.css +117 -0
  139. data/guides/assets/stylesheets/syntaxhighlighter/shThemeMDUltra.css +113 -0
  140. data/guides/assets/stylesheets/syntaxhighlighter/shThemeMidnight.css +113 -0
  141. data/guides/assets/stylesheets/syntaxhighlighter/shThemeRDark.css +113 -0
  142. data/guides/assets/stylesheets/syntaxhighlighter/shThemeRailsGuides.css +116 -0
  143. data/guides/code/getting_started/Gemfile +38 -0
  144. data/guides/code/getting_started/Gemfile.lock +150 -0
  145. data/guides/code/getting_started/README.rdoc +28 -0
  146. data/guides/code/getting_started/Rakefile +6 -0
  147. data/guides/code/getting_started/app/assets/images/rails.png +0 -0
  148. data/guides/code/getting_started/app/assets/javascripts/application.js +16 -0
  149. data/guides/code/getting_started/app/assets/javascripts/comments.js.coffee +3 -0
  150. data/guides/code/getting_started/app/assets/javascripts/posts.js.coffee +3 -0
  151. data/guides/code/getting_started/app/assets/javascripts/welcome.js.coffee +3 -0
  152. data/guides/code/getting_started/app/assets/stylesheets/application.css +13 -0
  153. data/guides/code/getting_started/app/assets/stylesheets/comments.css.scss +3 -0
  154. data/guides/code/getting_started/app/assets/stylesheets/posts.css.scss +3 -0
  155. data/guides/code/getting_started/app/assets/stylesheets/welcome.css.scss +3 -0
  156. data/guides/code/getting_started/app/controllers/application_controller.rb +5 -0
  157. data/guides/code/getting_started/app/controllers/comments_controller.rb +17 -0
  158. data/guides/code/getting_started/app/controllers/posts_controller.rb +47 -0
  159. data/guides/code/getting_started/app/controllers/welcome_controller.rb +4 -0
  160. data/guides/code/getting_started/app/helpers/application_helper.rb +2 -0
  161. data/guides/code/getting_started/app/helpers/comments_helper.rb +2 -0
  162. data/guides/code/getting_started/app/helpers/posts_helper.rb +2 -0
  163. data/guides/code/getting_started/app/helpers/welcome_helper.rb +2 -0
  164. data/guides/code/getting_started/app/models/comment.rb +3 -0
  165. data/guides/code/getting_started/app/models/post.rb +7 -0
  166. data/guides/code/getting_started/app/views/comments/_comment.html.erb +15 -0
  167. data/guides/code/getting_started/app/views/comments/_form.html.erb +13 -0
  168. data/guides/code/getting_started/app/views/layouts/application.html.erb +14 -0
  169. data/guides/code/getting_started/app/views/posts/_form.html.erb +27 -0
  170. data/guides/code/getting_started/app/views/posts/edit.html.erb +5 -0
  171. data/guides/code/getting_started/app/views/posts/index.html.erb +21 -0
  172. data/guides/code/getting_started/app/views/posts/new.html.erb +5 -0
  173. data/guides/code/getting_started/app/views/posts/show.html.erb +18 -0
  174. data/guides/code/getting_started/app/views/welcome/index.html.erb +3 -0
  175. data/guides/code/getting_started/bin/bundle +4 -0
  176. data/guides/code/getting_started/bin/rails +4 -0
  177. data/guides/code/getting_started/bin/rake +4 -0
  178. data/guides/code/getting_started/config.ru +4 -0
  179. data/guides/code/getting_started/config/application.rb +17 -0
  180. data/guides/code/getting_started/config/boot.rb +4 -0
  181. data/guides/code/getting_started/config/database.yml +25 -0
  182. data/guides/code/getting_started/config/environment.rb +5 -0
  183. data/guides/code/getting_started/config/environments/development.rb +30 -0
  184. data/guides/code/getting_started/config/environments/production.rb +80 -0
  185. data/guides/code/getting_started/config/environments/test.rb +36 -0
  186. data/guides/code/getting_started/config/initializers/backtrace_silencers.rb +7 -0
  187. data/guides/code/getting_started/config/initializers/filter_parameter_logging.rb +4 -0
  188. data/guides/code/getting_started/config/initializers/inflections.rb +16 -0
  189. data/guides/code/getting_started/config/initializers/locale.rb +9 -0
  190. data/guides/code/getting_started/config/initializers/mime_types.rb +5 -0
  191. data/guides/code/getting_started/config/initializers/secret_token.rb +12 -0
  192. data/guides/code/getting_started/config/initializers/session_store.rb +3 -0
  193. data/guides/code/getting_started/config/initializers/wrap_parameters.rb +14 -0
  194. data/guides/code/getting_started/config/locales/en.yml +23 -0
  195. data/guides/code/getting_started/config/routes.rb +7 -0
  196. data/guides/code/getting_started/db/migrate/20130122042648_create_posts.rb +10 -0
  197. data/guides/code/getting_started/db/migrate/20130122045842_create_comments.rb +11 -0
  198. data/guides/code/getting_started/db/schema.rb +33 -0
  199. data/guides/code/getting_started/db/seeds.rb +7 -0
  200. data/guides/code/getting_started/public/404.html +27 -0
  201. data/guides/code/getting_started/public/422.html +26 -0
  202. data/guides/code/getting_started/public/500.html +26 -0
  203. data/guides/code/getting_started/public/favicon.ico +0 -0
  204. data/guides/code/getting_started/public/robots.txt +5 -0
  205. data/guides/code/getting_started/test/controllers/comments_controller_test.rb +7 -0
  206. data/guides/code/getting_started/test/controllers/posts_controller_test.rb +7 -0
  207. data/guides/code/getting_started/test/controllers/welcome_controller_test.rb +9 -0
  208. data/guides/code/getting_started/test/fixtures/comments.yml +11 -0
  209. data/guides/code/getting_started/test/fixtures/posts.yml +9 -0
  210. data/guides/code/getting_started/test/helpers/comments_helper_test.rb +4 -0
  211. data/guides/code/getting_started/test/helpers/posts_helper_test.rb +4 -0
  212. data/guides/code/getting_started/test/helpers/welcome_helper_test.rb +4 -0
  213. data/guides/code/getting_started/test/models/comment_test.rb +7 -0
  214. data/guides/code/getting_started/test/models/post_test.rb +7 -0
  215. data/guides/code/getting_started/test/test_helper.rb +15 -0
  216. data/guides/rails_guides.rb +44 -0
  217. data/guides/rails_guides/generator.rb +248 -0
  218. data/guides/rails_guides/helpers.rb +51 -0
  219. data/guides/rails_guides/indexer.rb +68 -0
  220. data/guides/rails_guides/kindle.rb +119 -0
  221. data/guides/rails_guides/levenshtein.rb +31 -0
  222. data/guides/rails_guides/markdown.rb +163 -0
  223. data/guides/rails_guides/markdown/renderer.rb +82 -0
  224. data/guides/source/2_2_release_notes.md +435 -0
  225. data/guides/source/2_3_release_notes.md +621 -0
  226. data/guides/source/3_0_release_notes.md +614 -0
  227. data/guides/source/3_1_release_notes.md +556 -0
  228. data/guides/source/3_2_release_notes.md +565 -0
  229. data/guides/source/4_0_release_notes.md +228 -0
  230. data/guides/source/_license.html.erb +2 -0
  231. data/guides/source/_welcome.html.erb +19 -0
  232. data/guides/source/action_controller_overview.md +872 -0
  233. data/guides/source/action_mailer_basics.md +599 -0
  234. data/guides/source/action_view_overview.md +1565 -0
  235. data/guides/source/active_model_basics.md +200 -0
  236. data/guides/source/active_record_basics.md +370 -0
  237. data/guides/source/active_record_callbacks.md +358 -0
  238. data/guides/source/active_record_querying.md +1621 -0
  239. data/guides/source/active_record_validations.md +1128 -0
  240. data/guides/source/active_support_core_extensions.md +3791 -0
  241. data/guides/source/active_support_instrumentation.md +487 -0
  242. data/guides/source/api_documentation_guidelines.md +209 -0
  243. data/guides/source/asset_pipeline.md +832 -0
  244. data/guides/source/association_basics.md +2129 -0
  245. data/guides/source/caching_with_rails.md +350 -0
  246. data/guides/source/command_line.md +594 -0
  247. data/guides/source/configuring.md +736 -0
  248. data/guides/source/contributing_to_ruby_on_rails.md +455 -0
  249. data/guides/source/credits.html.erb +76 -0
  250. data/guides/source/debugging_rails_applications.md +675 -0
  251. data/guides/source/development_dependencies_install.md +195 -0
  252. data/guides/source/documents.yaml +179 -0
  253. data/guides/source/engines.md +961 -0
  254. data/guides/source/form_helpers.md +955 -0
  255. data/guides/source/generators.md +644 -0
  256. data/guides/source/getting_started.md +1775 -0
  257. data/guides/source/i18n.md +983 -0
  258. data/guides/source/index.html.erb +27 -0
  259. data/guides/source/initialization.md +562 -0
  260. data/guides/source/kindle/KINDLE.md +26 -0
  261. data/guides/source/kindle/copyright.html.erb +1 -0
  262. data/guides/source/kindle/layout.html.erb +27 -0
  263. data/guides/source/kindle/rails_guides.opf.erb +52 -0
  264. data/guides/source/kindle/toc.html.erb +24 -0
  265. data/guides/source/kindle/toc.ncx.erb +64 -0
  266. data/guides/source/kindle/welcome.html.erb +5 -0
  267. data/guides/source/layout.html.erb +148 -0
  268. data/guides/source/layouts_and_rendering.md +1132 -0
  269. data/guides/source/migrations.md +1059 -0
  270. data/guides/source/nested_model_forms.md +225 -0
  271. data/guides/source/plugins.md +435 -0
  272. data/guides/source/rails_application_templates.md +229 -0
  273. data/guides/source/rails_on_rack.md +342 -0
  274. data/guides/source/routing.md +1088 -0
  275. data/guides/source/ruby_on_rails_guides_guidelines.md +124 -0
  276. data/guides/source/security.md +973 -0
  277. data/guides/source/testing.md +981 -0
  278. data/guides/source/upgrading_ruby_on_rails.md +286 -0
  279. data/guides/source/working_with_javascript_in_rails.md +396 -0
  280. data/guides/w3c_validator.rb +95 -0
  281. metadata +315 -31
@@ -0,0 +1,981 @@
1
+ A Guide to Testing Rails Applications
2
+ =====================================
3
+
4
+ This guide covers built-in mechanisms offered by Rails to test your
5
+ application.
6
+
7
+ After reading this guide, you will know:
8
+
9
+ * Rails testing terminology.
10
+ * How to write unit, functional, and integration tests for your application.
11
+ * Other popular testing approaches and plugins.
12
+
13
+ --------------------------------------------------------------------------------
14
+
15
+ Why Write Tests for your Rails Applications?
16
+ --------------------------------------------
17
+
18
+ Rails makes it super easy to write your tests. It starts by producing skeleton test code while you are creating your models and controllers.
19
+
20
+ By simply running your Rails tests you can ensure your code adheres to the desired functionality even after some major code refactoring.
21
+
22
+ Rails tests can also simulate browser requests and thus you can test your application's response without having to test it through your browser.
23
+
24
+ Introduction to Testing
25
+ -----------------------
26
+
27
+ 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.
28
+
29
+ ### The Test Environment
30
+
31
+ 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`.
32
+
33
+ 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.
34
+
35
+ ### Rails Sets up for Testing from the Word Go
36
+
37
+ 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:
38
+
39
+ ```bash
40
+ $ ls -F test
41
+
42
+ fixtures/ functional/ integration/ test_helper.rb unit/
43
+ ```
44
+
45
+ The `unit` directory is meant to hold tests for your models, the `functional` 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.
46
+
47
+ Fixtures are a way of organizing test data; they reside in the `fixtures` folder.
48
+
49
+ The `test_helper.rb` file holds the default configuration for your tests.
50
+
51
+ ### The Low-Down on Fixtures
52
+
53
+ For good tests, you'll need to give some thought to setting up test data. In Rails, you can handle this by defining and customizing fixtures.
54
+
55
+ #### What Are Fixtures?
56
+
57
+ _Fixtures_ is a fancy word for sample data. Fixtures allow you to populate your testing database with predefined data before your tests run. Fixtures are database independent written in YAML. There is one file per model.
58
+
59
+ 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.
60
+
61
+ #### YAML
62
+
63
+ YAML-formatted fixtures are a very human-friendly way to describe your sample data. These types of fixtures have the **.yml** file extension (as in `users.yml`).
64
+
65
+ Here's a sample YAML fixture file:
66
+
67
+ ```yaml
68
+ # lo & behold! I am a YAML comment!
69
+ david:
70
+ name: David Heinemeier Hansson
71
+ birthday: 1979-10-15
72
+ profession: Systems development
73
+
74
+ steve:
75
+ name: Steve Ross Kellock
76
+ birthday: 1974-09-27
77
+ profession: guy with keyboard
78
+ ```
79
+
80
+ 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.
81
+
82
+ #### ERB'in It Up
83
+
84
+ 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:
85
+
86
+ ```erb
87
+ <% 1000.times do |n| %>
88
+ user_<%= n %>:
89
+ username: <%= "user%03d" % n %>
90
+ email: <%= "user%03d@example.com" % n %>
91
+ <% end %>
92
+ ```
93
+
94
+ #### Fixtures in Action
95
+
96
+ Rails by default automatically loads all fixtures from the `test/fixtures` folder for your unit and functional test. Loading involves three steps:
97
+
98
+ * Remove any existing data from the table corresponding to the fixture
99
+ * Load the fixture data into the table
100
+ * Dump the fixture data into a variable in case you want to access it directly
101
+
102
+ #### Fixtures are Active Record objects
103
+
104
+ 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:
105
+
106
+ ```ruby
107
+ # this will return the User object for the fixture named david
108
+ users(:david)
109
+
110
+ # this will return the property for david called id
111
+ users(:david).id
112
+
113
+ # one can also access methods available on the User class
114
+ email(david.girlfriend.email, david.location_tonight)
115
+ ```
116
+
117
+ Unit Testing your Models
118
+ ------------------------
119
+
120
+ In Rails, unit tests are what you write to test your models.
121
+
122
+ For this guide we will be using Rails _scaffolding_. It will create the model, a migration, controller and views for the new resource in a single operation. It will also create a full test suite following Rails best practices. I will be using examples from this generated code and will be supplementing it with additional examples where necessary.
123
+
124
+ NOTE: For more information on Rails <i>scaffolding</i>, refer to [Getting Started with Rails](getting_started.html)
125
+
126
+ When you use `rails generate scaffold`, for a resource among other things it creates a test stub in the `test/models` folder:
127
+
128
+ ```bash
129
+ $ rails generate scaffold post title:string body:text
130
+ ...
131
+ create app/models/post.rb
132
+ create test/models/post_test.rb
133
+ create test/fixtures/posts.yml
134
+ ...
135
+ ```
136
+
137
+ The default test stub in `test/models/post_test.rb` looks like this:
138
+
139
+ ```ruby
140
+ require 'test_helper'
141
+
142
+ class PostTest < ActiveSupport::TestCase
143
+ # Replace this with your real tests.
144
+ test "the truth" do
145
+ assert true
146
+ end
147
+ end
148
+ ```
149
+
150
+ A line by line examination of this file will help get you oriented to Rails testing code and terminology.
151
+
152
+ ```ruby
153
+ require 'test_helper'
154
+ ```
155
+
156
+ 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.
157
+
158
+ ```ruby
159
+ class PostTest < ActiveSupport::TestCase
160
+ ```
161
+
162
+ The `PostTest` class defines a _test case_ because it inherits from `ActiveSupport::TestCase`. `PostTest` thus has all the methods available from `ActiveSupport::TestCase`. You'll see those methods a little later in this guide.
163
+
164
+ Any method defined within a `Test::Unit` test case that begins with `test` (case sensitive) is simply called a test. So, `test_password`, `test_valid_password` and `testValidPassword` all are legal test names and are run automatically when the test case is run.
165
+
166
+ Rails adds a `test` method that takes a test name and a block. It generates a normal `Test::Unit` test with method names prefixed with `test_`. So,
167
+
168
+ ```ruby
169
+ test "the truth" do
170
+ assert true
171
+ end
172
+ ```
173
+
174
+ acts as if you had written
175
+
176
+ ```ruby
177
+ def test_the_truth
178
+ assert true
179
+ end
180
+ ```
181
+
182
+ only the `test` macro allows a more readable test name. You can still use regular method definitions though.
183
+
184
+ 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.
185
+
186
+ ```ruby
187
+ assert true
188
+ ```
189
+
190
+ 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:
191
+
192
+ * does this value = that value?
193
+ * is this object nil?
194
+ * does this line of code throw an exception?
195
+ * is the user's password greater than 5 characters?
196
+
197
+ Every test contains one or more assertions. Only when all the assertions are successful will the test pass.
198
+
199
+ ### Preparing your Application for Testing
200
+
201
+ Before you can run your tests, you need to ensure that the test database structure is current. For this you can use the following rake commands:
202
+
203
+ ```bash
204
+ $ rake db:migrate
205
+ ...
206
+ $ rake db:test:load
207
+ ```
208
+
209
+ The `rake db:migrate` above runs any pending migrations on the _development_ environment and updates `db/schema.rb`. The `rake db:test:load` recreates the test database from the current `db/schema.rb`. On subsequent attempts, it is a good idea to first run `db:test:prepare`, as it first checks for pending migrations and warns you appropriately.
210
+
211
+ NOTE: `db:test:prepare` will fail with an error if `db/schema.rb` doesn't exist.
212
+
213
+ #### Rake Tasks for Preparing your Application for Testing
214
+
215
+ | Tasks | Description |
216
+ | ------------------------------ | ------------------------------------------------------------------------- |
217
+ | `rake db:test:clone` | Recreate the test database from the current environment's database schema |
218
+ | `rake db:test:clone_structure` | Recreate the test database from the development structure |
219
+ | `rake db:test:load` | Recreate the test database from the current `schema.rb` |
220
+ | `rake db:test:prepare` | Check for pending migrations and load the test schema |
221
+ | `rake db:test:purge` | Empty the test database. |
222
+
223
+ TIP: You can see all these rake tasks and their descriptions by running `rake --tasks --describe`
224
+
225
+ ### Running Tests
226
+
227
+ Running a test is as simple as invoking the file containing the test cases through Ruby:
228
+
229
+ ```bash
230
+ $ ruby -Itest test/models/post_test.rb
231
+
232
+ Loaded suite models/post_test
233
+ Started
234
+ .
235
+ Finished in 0.023513 seconds.
236
+
237
+ 1 tests, 1 assertions, 0 failures, 0 errors
238
+ ```
239
+
240
+ This will run all the 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.
241
+
242
+ You can also run a particular test method from the test case by using the `-n` switch with the `test method name`.
243
+
244
+ ```bash
245
+ $ ruby -Itest test/models/post_test.rb -n test_the_truth
246
+
247
+ Loaded suite models/post_test
248
+ Started
249
+ .
250
+ Finished in 0.023513 seconds.
251
+
252
+ 1 tests, 1 assertions, 0 failures, 0 errors
253
+ ```
254
+
255
+ 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.
256
+
257
+ To see how a test failure is reported, you can add a failing test to the `post_test.rb` test case.
258
+
259
+ ```ruby
260
+ test "should not save post without title" do
261
+ post = Post.new
262
+ assert !post.save
263
+ end
264
+ ```
265
+
266
+ Let us run this newly added test.
267
+
268
+ ```bash
269
+ $ ruby unit/post_test.rb -n test_should_not_save_post_without_title
270
+ Loaded suite -e
271
+ Started
272
+ F
273
+ Finished in 0.102072 seconds.
274
+
275
+ 1) Failure:
276
+ test_should_not_save_post_without_title(PostTest) [/test/models/post_test.rb:6]:
277
+ <false> is not true.
278
+
279
+ 1 tests, 1 assertions, 1 failures, 0 errors
280
+ ```
281
+
282
+ 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:
283
+
284
+ ```ruby
285
+ test "should not save post without title" do
286
+ post = Post.new
287
+ assert !post.save, "Saved the post without a title"
288
+ end
289
+ ```
290
+
291
+ Running this test shows the friendlier assertion message:
292
+
293
+ ```bash
294
+ 1) Failure:
295
+ test_should_not_save_post_without_title(PostTest) [/test/models/post_test.rb:6]:
296
+ Saved the post without a title.
297
+ <false> is not true.
298
+ ```
299
+
300
+ Now to get this test to pass we can add a model level validation for the _title_ field.
301
+
302
+ ```ruby
303
+ class Post < ActiveRecord::Base
304
+ validates :title, presence: true
305
+ end
306
+ ```
307
+
308
+ Now the test should pass. Let us verify by running the test again:
309
+
310
+ ```bash
311
+ $ ruby unit/post_test.rb -n test_should_not_save_post_without_title
312
+ Loaded suite unit/post_test
313
+ Started
314
+ .
315
+ Finished in 0.193608 seconds.
316
+
317
+ 1 tests, 1 assertions, 0 failures, 0 errors
318
+ ```
319
+
320
+ 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).
321
+
322
+ 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).
323
+
324
+ To see how an error gets reported, here's a test containing an error:
325
+
326
+ ```ruby
327
+ test "should report error" do
328
+ # some_undefined_variable is not defined elsewhere in the test case
329
+ some_undefined_variable
330
+ assert true
331
+ end
332
+ ```
333
+
334
+ Now you can see even more output in the console from running the tests:
335
+
336
+ ```bash
337
+ $ ruby unit/post_test.rb -n test_should_report_error
338
+ Loaded suite -e
339
+ Started
340
+ E
341
+ Finished in 0.082603 seconds.
342
+
343
+ 1) Error:
344
+ test_should_report_error(PostTest):
345
+ NameError: undefined local variable or method `some_undefined_variable' for #<PostTest:0x249d354>
346
+ /test/models/post_test.rb:6:in `test_should_report_error'
347
+
348
+ 1 tests, 0 assertions, 0 failures, 1 errors
349
+ ```
350
+
351
+ Notice the 'E' in the output. It denotes a test with error.
352
+
353
+ 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.
354
+
355
+ ### What to Include in Your Unit Tests
356
+
357
+ 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.
358
+
359
+ ### Assertions Available
360
+
361
+ 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.
362
+
363
+ There are a bunch of different types of assertions you can use. Here's the complete list of assertions that ship with `test/unit`, the 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.
364
+
365
+ | Assertion | Purpose |
366
+ | ---------------------------------------------------------------- | ------- |
367
+ | `assert( boolean, [msg] )` | Ensures that the object/expression is true.|
368
+ | `assert_equal( expected, actual, [msg] )` | Ensures that `expected == actual` is true.|
369
+ | `assert_not_equal( expected, actual, [msg] )` | Ensures that `expected != actual` is true.|
370
+ | `assert_same( expected, actual, [msg] )` | Ensures that `expected.equal?(actual)` is true.|
371
+ | `assert_not_same( expected, actual, [msg] )` | Ensures that `!expected.equal?(actual)` is true.|
372
+ | `assert_nil( obj, [msg] )` | Ensures that `obj.nil?` is true.|
373
+ | `assert_not_nil( obj, [msg] )` | Ensures that `!obj.nil?` is true.|
374
+ | `assert_match( regexp, string, [msg] )` | Ensures that a string matches the regular expression.|
375
+ | `assert_no_match( regexp, string, [msg] )` | Ensures that a string doesn't match the regular expression.|
376
+ | `assert_in_delta( expecting, actual, delta, [msg] )` | Ensures that the numbers `expecting` and `actual` are within `delta` of each other.|
377
+ | `assert_throws( symbol, [msg] ) { block }` | Ensures that the given block throws the symbol.|
378
+ | `assert_raise( exception1, exception2, ... ) { block }` | Ensures that the given block raises one of the given exceptions.|
379
+ | `assert_nothing_raised( exception1, exception2, ... ) { block }` | Ensures that the given block doesn't raise one of the given exceptions.|
380
+ | `assert_instance_of( class, obj, [msg] )` | Ensures that `obj` is of the `class` type.|
381
+ | `assert_kind_of( class, obj, [msg] )` | Ensures that `obj` is or descends from `class`.|
382
+ | `assert_respond_to( obj, symbol, [msg] )` | Ensures that `obj` has a method called `symbol`.|
383
+ | `assert_operator( obj1, operator, obj2, [msg] )` | Ensures that `obj1.operator(obj2)` is true.|
384
+ | `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?|
385
+ | `flunk( [msg] )` | Ensures failure. This is useful to explicitly mark a test that isn't finished yet.|
386
+
387
+ 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.
388
+
389
+ NOTE: Creating your own assertions is an advanced topic that we won't cover in this tutorial.
390
+
391
+ ### Rails Specific Assertions
392
+
393
+ Rails adds some custom assertions of its own to the `test/unit` framework:
394
+
395
+ | Assertion | Purpose |
396
+ | --------------------------------------------------------------------------------- | ------- |
397
+ | `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.|
398
+ | `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.|
399
+ | `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.|
400
+ | `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.|
401
+ | `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|
402
+ | `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.|
403
+ | `assert_template(expected = nil, message=nil)` | Asserts that the request was rendered with the appropriate template file.|
404
+
405
+ You'll see the usage of some of these assertions in the next chapter.
406
+
407
+ Functional Tests for Your Controllers
408
+ -------------------------------------
409
+
410
+ 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.
411
+
412
+ ### What to Include in your Functional Tests
413
+
414
+ You should test for things such as:
415
+
416
+ * was the web request successful?
417
+ * was the user redirected to the right page?
418
+ * was the user successfully authenticated?
419
+ * was the correct object stored in the response template?
420
+ * was the appropriate message displayed to the user in the view?
421
+
422
+ Now that we have used Rails scaffold generator for our `Post` resource, it has already created the controller code and tests. You can take look at the file `posts_controller_test.rb` in the `test/controllers` directory.
423
+
424
+ Let me take you through one such test, `test_should_get_index` from the file `posts_controller_test.rb`.
425
+
426
+ ```ruby
427
+ test "should get index" do
428
+ get :index
429
+ assert_response :success
430
+ assert_not_nil assigns(:posts)
431
+ end
432
+ ```
433
+
434
+ In the `test_should_get_index` test, Rails simulates a request on the action called `index`, making sure the request was successful and also ensuring that it assigns a valid `posts` instance variable.
435
+
436
+ The `get` method kicks off the web request and populates the results into the response. It accepts 4 arguments:
437
+
438
+ * The action of the controller you are requesting. This can be in the form of a string or a symbol.
439
+ * An optional hash of request parameters to pass into the action (eg. query string parameters or post variables).
440
+ * An optional hash of session variables to pass along with the request.
441
+ * An optional hash of flash values.
442
+
443
+ Example: Calling the `:show` action, passing an `id` of 12 as the `params` and setting a `user_id` of 5 in the session:
444
+
445
+ ```ruby
446
+ get(:show, {'id' => "12"}, {'user_id' => 5})
447
+ ```
448
+
449
+ Another example: Calling the `:view` action, passing an `id` of 12 as the `params`, this time with no session, but with a flash message.
450
+
451
+ ```ruby
452
+ get(:view, {'id' => '12'}, nil, {'message' => 'booya!'})
453
+ ```
454
+
455
+ NOTE: If you try running `test_should_create_post` test from `posts_controller_test.rb` it will fail on account of the newly added model level validation and rightly so.
456
+
457
+ Let us modify `test_should_create_post` test in `posts_controller_test.rb` so that all our test pass:
458
+
459
+ ```ruby
460
+ test "should create post" do
461
+ assert_difference('Post.count') do
462
+ post :create, post: {title: 'Some title'}
463
+ end
464
+
465
+ assert_redirected_to post_path(assigns(:post))
466
+ end
467
+ ```
468
+
469
+ Now you can try running all the tests and they should pass.
470
+
471
+ ### Available Request Types for Functional Tests
472
+
473
+ 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:
474
+
475
+ * `get`
476
+ * `post`
477
+ * `patch`
478
+ * `put`
479
+ * `head`
480
+ * `delete`
481
+
482
+ 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.
483
+
484
+ 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.
485
+
486
+ ### The Four Hashes of the Apocalypse
487
+
488
+ After a request has been made by using one of the 5 methods (`get`, `post`, etc.) and processed, you will have 4 Hash objects ready for use:
489
+
490
+ * `assigns` - Any objects that are stored as instance variables in actions for use in views.
491
+ * `cookies` - Any cookies that are set.
492
+ * `flash` - Any objects living in the flash.
493
+ * `session` - Any object living in session variables.
494
+
495
+ 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:
496
+
497
+ ```ruby
498
+ flash["gordon"] flash[:gordon]
499
+ session["shmession"] session[:shmession]
500
+ cookies["are_good_for_u"] cookies[:are_good_for_u]
501
+
502
+ # Because you can't use assigns[:something] for historical reasons:
503
+ assigns["something"] assigns(:something)
504
+ ```
505
+
506
+ ### Instance Variables Available
507
+
508
+ You also have access to three instance variables in your functional tests:
509
+
510
+ * `@controller` - The controller processing the request
511
+ * `@request` - The request
512
+ * `@response` - The response
513
+
514
+ ### Testing Templates and Layouts
515
+
516
+ If you want to make sure that the response rendered the correct template and layout, you can use the `assert_template`
517
+ method:
518
+
519
+ ```ruby
520
+ test "index should render correct template and layout" do
521
+ get :index
522
+ assert_template :index
523
+ assert_template layout: "layouts/application"
524
+ end
525
+ ```
526
+
527
+ Note that you cannot test for template and layout at the same time, with one call to `assert_template` method.
528
+ Also, for the `layout` test, you can give a regular expression instead of a string, but using the string, makes
529
+ things clearer. On the other hand, you have to include the "layouts" directory name even if you save your layout
530
+ file in this standard layout directory. Hence,
531
+
532
+ ```ruby
533
+ assert_template layout: "application"
534
+ ```
535
+
536
+ will not work.
537
+
538
+ If your view renders any partial, when asserting for the layout, you have to assert for the partial at the same time.
539
+ Otherwise, assertion will fail.
540
+
541
+ Hence:
542
+
543
+ ```ruby
544
+ test "new should render correct layout" do
545
+ get :new
546
+ assert_template layout: "layouts/application", partial: "_form"
547
+ end
548
+ ```
549
+
550
+ 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.
551
+
552
+ ### A Fuller Functional Test Example
553
+
554
+ Here's another example that uses `flash`, `assert_redirected_to`, and `assert_difference`:
555
+
556
+ ```ruby
557
+ test "should create post" do
558
+ assert_difference('Post.count') do
559
+ post :create, post: {title: 'Hi', body: 'This is my first post.'}
560
+ end
561
+ assert_redirected_to post_path(assigns(:post))
562
+ assert_equal 'Post was successfully created.', flash[:notice]
563
+ end
564
+ ```
565
+
566
+ ### Testing Views
567
+
568
+ 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.
569
+
570
+ NOTE: You may find references to `assert_tag` in other documentation, but this is now deprecated in favor of `assert_select`.
571
+
572
+ There are two forms of `assert_select`:
573
+
574
+ `assert_select(selector, [equality], [message])` ensures that the equality condition is met on the selected elements through the selector. The selector may be a CSS selector expression (String), an expression with substitution values, or an `HTML::Selector` object.
575
+
576
+ `assert_select(element, selector, [equality], [message])` ensures that the equality condition is met on all the selected elements through the selector starting from the _element_ (instance of `HTML::Node`) and its descendants.
577
+
578
+ For example, you could verify the contents on the title element in your response with:
579
+
580
+ ```ruby
581
+ assert_select 'title', "Welcome to Rails Testing Guide"
582
+ ```
583
+
584
+ 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:
585
+
586
+ ```ruby
587
+ assert_select 'ul.navigation' do
588
+ assert_select 'li.menu_item'
589
+ end
590
+ ```
591
+
592
+ 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.
593
+
594
+ ```ruby
595
+ assert_select "ol" do |elements|
596
+ elements.each do |element|
597
+ assert_select element, "li", 4
598
+ end
599
+ end
600
+
601
+ assert_select "ol" do
602
+ assert_select "li", 8
603
+ end
604
+ ```
605
+
606
+ The `assert_select` assertion is quite powerful. For more advanced usage, refer to its [documentation](http://api.rubyonrails.org/classes/ActionDispatch/Assertions/SelectorAssertions.html).
607
+
608
+ #### Additional View-Based Assertions
609
+
610
+ There are more assertions that are primarily used in testing views:
611
+
612
+ | Assertion | Purpose |
613
+ | ---------------------------------------------------------- | ------- |
614
+ | `assert_select_email` | Allows you to make assertions on the body of an e-mail. |
615
+ | `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.|
616
+ | `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.|
617
+
618
+ Here's an example of using `assert_select_email`:
619
+
620
+ ```ruby
621
+ assert_select_email do
622
+ assert_select 'small', 'Please click the "Unsubscribe" link if you want to opt-out.'
623
+ end
624
+ ```
625
+
626
+ Integration Testing
627
+ -------------------
628
+
629
+ 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.
630
+
631
+ 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.
632
+
633
+ ```bash
634
+ $ rails generate integration_test user_flows
635
+ exists test/integration/
636
+ create test/integration/user_flows_test.rb
637
+ ```
638
+
639
+ Here's what a freshly-generated integration test looks like:
640
+
641
+ ```ruby
642
+ require 'test_helper'
643
+
644
+ class UserFlowsTest < ActionDispatch::IntegrationTest
645
+ fixtures :all
646
+
647
+ # Replace this with your real tests.
648
+ test "the truth" do
649
+ assert true
650
+ end
651
+ end
652
+ ```
653
+
654
+ 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.
655
+
656
+ ### Helpers Available for Integration Tests
657
+
658
+ In addition to the standard testing helpers, there are some additional helpers available to integration tests:
659
+
660
+ | Helper | Purpose |
661
+ | ------------------------------------------------------------------ | ------- |
662
+ | `https?` | Returns `true` if the session is mimicking a secure HTTPS request.|
663
+ | `https!` | Allows you to mimic a secure HTTPS request.|
664
+ | `host!` | Allows you to set the host name to use in the next request.|
665
+ | `redirect?` | Returns `true` if the last request was a redirect.|
666
+ | `follow_redirect!` | Follows a single redirect response.|
667
+ | `request_via_redirect(http_method, path, [parameters], [headers])` | Allows you to make an HTTP request and follow any subsequent redirects.|
668
+ | `post_via_redirect(path, [parameters], [headers])` | Allows you to make an HTTP POST request and follow any subsequent redirects.|
669
+ | `get_via_redirect(path, [parameters], [headers])` | Allows you to make an HTTP GET request and follow any subsequent redirects.|
670
+ | `patch_via_redirect(path, [parameters], [headers])` | Allows you to make an HTTP PATCH request and follow any subsequent redirects.|
671
+ | `put_via_redirect(path, [parameters], [headers])` | Allows you to make an HTTP PUT request and follow any subsequent redirects.|
672
+ | `delete_via_redirect(path, [parameters], [headers])` | Allows you to make an HTTP DELETE request and follow any subsequent redirects.|
673
+ | `open_session` | Opens a new session instance.|
674
+
675
+ ### Integration Testing Examples
676
+
677
+ A simple integration test that exercises multiple controllers:
678
+
679
+ ```ruby
680
+ require 'test_helper'
681
+
682
+ class UserFlowsTest < ActionDispatch::IntegrationTest
683
+ fixtures :users
684
+
685
+ test "login and browse site" do
686
+ # login via https
687
+ https!
688
+ get "/login"
689
+ assert_response :success
690
+
691
+ post_via_redirect "/login", username: users(:avs).username, password: users(:avs).password
692
+ assert_equal '/welcome', path
693
+ assert_equal 'Welcome avs!', flash[:notice]
694
+
695
+ https!(false)
696
+ get "/posts/all"
697
+ assert_response :success
698
+ assert assigns(:products)
699
+ end
700
+ end
701
+ ```
702
+
703
+ 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.
704
+
705
+ Here's an example of multiple sessions and custom DSL in an integration test
706
+
707
+ ```ruby
708
+ require 'test_helper'
709
+
710
+ class UserFlowsTest < ActionDispatch::IntegrationTest
711
+ fixtures :users
712
+
713
+ test "login and browse site" do
714
+
715
+ # User avs logs in
716
+ avs = login(:avs)
717
+ # User guest logs in
718
+ guest = login(:guest)
719
+
720
+ # Both are now available in different sessions
721
+ assert_equal 'Welcome avs!', avs.flash[:notice]
722
+ assert_equal 'Welcome guest!', guest.flash[:notice]
723
+
724
+ # User avs can browse site
725
+ avs.browses_site
726
+ # User guest can browse site as well
727
+ guest.browses_site
728
+
729
+ # Continue with other assertions
730
+ end
731
+
732
+ private
733
+
734
+ module CustomDsl
735
+ def browses_site
736
+ get "/products/all"
737
+ assert_response :success
738
+ assert assigns(:products)
739
+ end
740
+ end
741
+
742
+ def login(user)
743
+ open_session do |sess|
744
+ sess.extend(CustomDsl)
745
+ u = users(user)
746
+ sess.https!
747
+ sess.post "/login", username: u.username, password: u.password
748
+ assert_equal '/welcome', path
749
+ sess.https!(false)
750
+ end
751
+ end
752
+ end
753
+ ```
754
+
755
+ Rake Tasks for Running your Tests
756
+ ---------------------------------
757
+
758
+ You don't need to set up and run your tests by hand on a test-by-test basis. Rails comes with a number of rake tasks to help in testing. The table below lists all rake tasks that come along in the default Rakefile when you initiate a Rails project.
759
+
760
+ | Tasks | Description |
761
+ | ------------------------------- | ----------- |
762
+ | `rake test` | Runs all unit, functional and integration tests. You can also simply run `rake` as the _test_ target is the default.|
763
+ | `rake test:controllers` | Runs all the controller tests from `test/controllers`|
764
+ | `rake test:functionals` | Runs all the functional tests from `test/controllers`, `test/mailers`, and `test/functional`|
765
+ | `rake test:helpers` | Runs all the helper tests from `test/helpers`|
766
+ | `rake test:integration` | Runs all the integration tests from `test/integration`|
767
+ | `rake test:mailers` | Runs all the mailer tests from `test/mailers`|
768
+ | `rake test:models` | Runs all the model tests from `test/models`|
769
+ | `rake test:recent` | Tests recent changes|
770
+ | `rake test:uncommitted` | Runs all the tests which are uncommitted. Supports Subversion and Git|
771
+ | `rake test:units` | Runs all the unit tests from `test/models`, `test/helpers`, and `test/unit`|
772
+
773
+
774
+ Brief Note About `Test::Unit`
775
+ -----------------------------
776
+
777
+ Ruby ships with a boat load of libraries. Ruby 1.8 provides `Test::Unit`, a framework for unit testing in Ruby. All the basic assertions discussed above are actually defined in `Test::Unit::Assertions`. The class `ActiveSupport::TestCase` which we have been using in our unit and functional tests extends `Test::Unit::TestCase`, allowing
778
+ us to use all of the basic assertions in our tests.
779
+
780
+ Ruby 1.9 introduced `MiniTest`, an updated version of `Test::Unit` which provides a backwards compatible API for `Test::Unit`. You could also use `MiniTest` in Ruby 1.8 by installing the `minitest` gem.
781
+
782
+ NOTE: For more information on `Test::Unit`, refer to [test/unit Documentation](http://ruby-doc.org/stdlib/libdoc/test/unit/rdoc/)
783
+ For more information on `MiniTest`, refer to [Minitest](http://www.ruby-doc.org/stdlib-1.9.3/libdoc/minitest/unit/rdoc/)
784
+
785
+ Setup and Teardown
786
+ ------------------
787
+
788
+ If you would like to run a block of code before the start of each test and another block of code after the end of each test you have two special callbacks for your rescue. Let's take note of this by looking at an example for our functional test in `Posts` controller:
789
+
790
+ ```ruby
791
+ require 'test_helper'
792
+
793
+ class PostsControllerTest < ActionController::TestCase
794
+
795
+ # called before every single test
796
+ def setup
797
+ @post = posts(:one)
798
+ end
799
+
800
+ # called after every single test
801
+ def teardown
802
+ # as we are re-initializing @post before every test
803
+ # setting it to nil here is not essential but I hope
804
+ # you understand how you can use the teardown method
805
+ @post = nil
806
+ end
807
+
808
+ test "should show post" do
809
+ get :show, id: @post.id
810
+ assert_response :success
811
+ end
812
+
813
+ test "should destroy post" do
814
+ assert_difference('Post.count', -1) do
815
+ delete :destroy, id: @post.id
816
+ end
817
+
818
+ assert_redirected_to posts_path
819
+ end
820
+
821
+ end
822
+ ```
823
+
824
+ Above, the `setup` method is called before each test and so `@post` is available for each of the tests. Rails implements `setup` and `teardown` as `ActiveSupport::Callbacks`. Which essentially means you need not only use `setup` and `teardown` as methods in your tests. You could specify them by using:
825
+
826
+ * a block
827
+ * a method (like in the earlier example)
828
+ * a method name as a symbol
829
+ * a lambda
830
+
831
+ Let's see the earlier example by specifying `setup` callback by specifying a method name as a symbol:
832
+
833
+ ```ruby
834
+ require 'test_helper'
835
+
836
+ class PostsControllerTest < ActionController::TestCase
837
+
838
+ # called before every single test
839
+ setup :initialize_post
840
+
841
+ # called after every single test
842
+ def teardown
843
+ @post = nil
844
+ end
845
+
846
+ test "should show post" do
847
+ get :show, id: @post.id
848
+ assert_response :success
849
+ end
850
+
851
+ test "should update post" do
852
+ patch :update, id: @post.id, post: {}
853
+ assert_redirected_to post_path(assigns(:post))
854
+ end
855
+
856
+ test "should destroy post" do
857
+ assert_difference('Post.count', -1) do
858
+ delete :destroy, id: @post.id
859
+ end
860
+
861
+ assert_redirected_to posts_path
862
+ end
863
+
864
+ private
865
+
866
+ def initialize_post
867
+ @post = posts(:one)
868
+ end
869
+
870
+ end
871
+ ```
872
+
873
+ Testing Routes
874
+ --------------
875
+
876
+ 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 `Posts` controller above should look like:
877
+
878
+ ```ruby
879
+ test "should route to post" do
880
+ assert_routing '/posts/1', {controller: "posts", action: "show", id: "1"}
881
+ end
882
+ ```
883
+
884
+ Testing Your Mailers
885
+ --------------------
886
+
887
+ Testing mailer classes requires some specific tools to do a thorough job.
888
+
889
+ ### Keeping the Postman in Check
890
+
891
+ Your mailer classes — like every other part of your Rails application — should be tested to ensure that it is working as expected.
892
+
893
+ The goals of testing your mailer classes are to ensure that:
894
+
895
+ * emails are being processed (created and sent)
896
+ * the email content is correct (subject, sender, body, etc)
897
+ * the right emails are being sent at the right times
898
+
899
+ #### From All Sides
900
+
901
+ 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.
902
+
903
+ ### Unit Testing
904
+
905
+ 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.
906
+
907
+ #### Revenge of the Fixtures
908
+
909
+ 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.
910
+
911
+ 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.
912
+
913
+ #### The Basic Test Case
914
+
915
+ 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.
916
+
917
+ ```ruby
918
+ require 'test_helper'
919
+
920
+ class UserMailerTest < ActionMailer::TestCase
921
+ tests UserMailer
922
+ test "invite" do
923
+ @expected.from = 'me@example.com'
924
+ @expected.to = 'friend@example.com'
925
+ @expected.subject = "You have been invited by #{@expected.from}"
926
+ @expected.body = read_fixture('invite')
927
+ @expected.date = Time.now
928
+
929
+ assert_equal @expected.encoded, UserMailer.create_invite('me@example.com', 'friend@example.com', @expected.date).encoded
930
+ end
931
+
932
+ end
933
+ ```
934
+
935
+ In this test, `@expected` is an instance of `TMail::Mail` that you can use in your tests. It is defined in `ActionMailer::TestCase`. The test above uses `@expected` to construct an email, which it then asserts with email created by the custom mailer. The `invite` fixture is the body of the email and is used as the sample content to assert against. The helper `read_fixture` is used to read in the content from this file.
936
+
937
+ Here's the content of the `invite` fixture:
938
+
939
+ ```
940
+ Hi friend@example.com,
941
+
942
+ You have been invited.
943
+
944
+ Cheers!
945
+ ```
946
+
947
+ This is the right time to understand a little more about writing tests for your mailers. The line `ActionMailer::Base.delivery_method = :test` in `config/environments/test.rb` sets the delivery method to test mode so that email will not actually be delivered (useful to avoid spamming your users while testing) but instead it will be appended to an array (`ActionMailer::Base.deliveries`).
948
+
949
+ This way, emails are not actually sent, simply constructed. The precise content of the email can then be checked against what is expected, as in the example above.
950
+
951
+ ### Functional Testing
952
+
953
+ 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:
954
+
955
+ ```ruby
956
+ require 'test_helper'
957
+
958
+ class UserControllerTest < ActionController::TestCase
959
+ test "invite friend" do
960
+ assert_difference 'ActionMailer::Base.deliveries.size', +1 do
961
+ post :invite_friend, email: 'friend@example.com'
962
+ end
963
+ invite_email = ActionMailer::Base.deliveries.last
964
+
965
+ assert_equal "You have been invited by me@example.com", invite_email.subject
966
+ assert_equal 'friend@example.com', invite_email.to[0]
967
+ assert_match(/Hi friend@example.com/, invite_email.body)
968
+ end
969
+ end
970
+ ```
971
+
972
+ Other Testing Approaches
973
+ ------------------------
974
+
975
+ The built-in `test/unit` based testing is not the only way to test Rails applications. Rails developers have come up with a wide variety of other approaches and aids for testing, including:
976
+
977
+ * [NullDB](http://avdi.org/projects/nulldb/), a way to speed up testing by avoiding database use.
978
+ * [Factory Girl](https://github.com/thoughtbot/factory_girl/tree/master), a replacement for fixtures.
979
+ * [Machinist](https://github.com/notahat/machinist/tree/master), another replacement for fixtures.
980
+ * [Shoulda](http://www.thoughtbot.com/projects/shoulda), an extension to `test/unit` with additional helpers, macros, and assertions.
981
+ * [RSpec](http://relishapp.com/rspec), a behavior-driven development framework