rails 4.1.4 → 6.0.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (284) hide show
  1. checksums.yaml +5 -5
  2. data/README.md +55 -34
  3. metadata +93 -311
  4. data/guides/CHANGELOG.md +0 -41
  5. data/guides/Rakefile +0 -77
  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 -53
  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 -710
  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 -53
  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/code/getting_started/Gemfile +0 -40
  148. data/guides/code/getting_started/Gemfile.lock +0 -125
  149. data/guides/code/getting_started/README.rdoc +0 -28
  150. data/guides/code/getting_started/Rakefile +0 -6
  151. data/guides/code/getting_started/app/assets/javascripts/application.js +0 -15
  152. data/guides/code/getting_started/app/assets/javascripts/comments.js.coffee +0 -3
  153. data/guides/code/getting_started/app/assets/javascripts/posts.js.coffee +0 -3
  154. data/guides/code/getting_started/app/assets/javascripts/welcome.js.coffee +0 -3
  155. data/guides/code/getting_started/app/assets/stylesheets/application.css +0 -13
  156. data/guides/code/getting_started/app/assets/stylesheets/comments.css.scss +0 -3
  157. data/guides/code/getting_started/app/assets/stylesheets/posts.css.scss +0 -3
  158. data/guides/code/getting_started/app/assets/stylesheets/welcome.css.scss +0 -3
  159. data/guides/code/getting_started/app/controllers/application_controller.rb +0 -5
  160. data/guides/code/getting_started/app/controllers/comments_controller.rb +0 -23
  161. data/guides/code/getting_started/app/controllers/posts_controller.rb +0 -53
  162. data/guides/code/getting_started/app/controllers/welcome_controller.rb +0 -4
  163. data/guides/code/getting_started/app/helpers/application_helper.rb +0 -2
  164. data/guides/code/getting_started/app/helpers/comments_helper.rb +0 -2
  165. data/guides/code/getting_started/app/helpers/posts_helper.rb +0 -2
  166. data/guides/code/getting_started/app/helpers/welcome_helper.rb +0 -2
  167. data/guides/code/getting_started/app/models/comment.rb +0 -3
  168. data/guides/code/getting_started/app/models/post.rb +0 -7
  169. data/guides/code/getting_started/app/views/comments/_comment.html.erb +0 -15
  170. data/guides/code/getting_started/app/views/comments/_form.html.erb +0 -13
  171. data/guides/code/getting_started/app/views/layouts/application.html.erb +0 -14
  172. data/guides/code/getting_started/app/views/posts/_form.html.erb +0 -27
  173. data/guides/code/getting_started/app/views/posts/edit.html.erb +0 -5
  174. data/guides/code/getting_started/app/views/posts/index.html.erb +0 -21
  175. data/guides/code/getting_started/app/views/posts/new.html.erb +0 -5
  176. data/guides/code/getting_started/app/views/posts/show.html.erb +0 -18
  177. data/guides/code/getting_started/app/views/welcome/index.html.erb +0 -4
  178. data/guides/code/getting_started/bin/bundle +0 -4
  179. data/guides/code/getting_started/bin/rails +0 -4
  180. data/guides/code/getting_started/bin/rake +0 -4
  181. data/guides/code/getting_started/config/application.rb +0 -18
  182. data/guides/code/getting_started/config/boot.rb +0 -4
  183. data/guides/code/getting_started/config/database.yml +0 -25
  184. data/guides/code/getting_started/config/environment.rb +0 -5
  185. data/guides/code/getting_started/config/environments/development.rb +0 -30
  186. data/guides/code/getting_started/config/environments/production.rb +0 -80
  187. data/guides/code/getting_started/config/environments/test.rb +0 -36
  188. data/guides/code/getting_started/config/initializers/backtrace_silencers.rb +0 -7
  189. data/guides/code/getting_started/config/initializers/filter_parameter_logging.rb +0 -4
  190. data/guides/code/getting_started/config/initializers/inflections.rb +0 -16
  191. data/guides/code/getting_started/config/initializers/locale.rb +0 -9
  192. data/guides/code/getting_started/config/initializers/mime_types.rb +0 -5
  193. data/guides/code/getting_started/config/initializers/secret_token.rb +0 -12
  194. data/guides/code/getting_started/config/initializers/session_store.rb +0 -3
  195. data/guides/code/getting_started/config/initializers/wrap_parameters.rb +0 -14
  196. data/guides/code/getting_started/config/locales/en.yml +0 -23
  197. data/guides/code/getting_started/config/routes.rb +0 -7
  198. data/guides/code/getting_started/config.ru +0 -4
  199. data/guides/code/getting_started/db/migrate/20130122042648_create_posts.rb +0 -10
  200. data/guides/code/getting_started/db/migrate/20130122045842_create_comments.rb +0 -11
  201. data/guides/code/getting_started/db/schema.rb +0 -33
  202. data/guides/code/getting_started/db/seeds.rb +0 -7
  203. data/guides/code/getting_started/public/404.html +0 -60
  204. data/guides/code/getting_started/public/422.html +0 -60
  205. data/guides/code/getting_started/public/500.html +0 -59
  206. data/guides/code/getting_started/public/favicon.ico +0 -0
  207. data/guides/code/getting_started/public/robots.txt +0 -5
  208. data/guides/code/getting_started/test/controllers/comments_controller_test.rb +0 -7
  209. data/guides/code/getting_started/test/controllers/posts_controller_test.rb +0 -7
  210. data/guides/code/getting_started/test/controllers/welcome_controller_test.rb +0 -9
  211. data/guides/code/getting_started/test/fixtures/comments.yml +0 -11
  212. data/guides/code/getting_started/test/fixtures/posts.yml +0 -9
  213. data/guides/code/getting_started/test/helpers/comments_helper_test.rb +0 -4
  214. data/guides/code/getting_started/test/helpers/posts_helper_test.rb +0 -4
  215. data/guides/code/getting_started/test/helpers/welcome_helper_test.rb +0 -4
  216. data/guides/code/getting_started/test/models/comment_test.rb +0 -7
  217. data/guides/code/getting_started/test/models/post_test.rb +0 -7
  218. data/guides/code/getting_started/test/test_helper.rb +0 -12
  219. data/guides/rails_guides/generator.rb +0 -248
  220. data/guides/rails_guides/helpers.rb +0 -53
  221. data/guides/rails_guides/indexer.rb +0 -68
  222. data/guides/rails_guides/kindle.rb +0 -119
  223. data/guides/rails_guides/levenshtein.rb +0 -31
  224. data/guides/rails_guides/markdown/renderer.rb +0 -82
  225. data/guides/rails_guides/markdown.rb +0 -163
  226. data/guides/rails_guides.rb +0 -63
  227. data/guides/source/2_2_release_notes.md +0 -435
  228. data/guides/source/2_3_release_notes.md +0 -621
  229. data/guides/source/3_0_release_notes.md +0 -611
  230. data/guides/source/3_1_release_notes.md +0 -556
  231. data/guides/source/3_2_release_notes.md +0 -565
  232. data/guides/source/4_0_release_notes.md +0 -276
  233. data/guides/source/4_1_release_notes.md +0 -731
  234. data/guides/source/_license.html.erb +0 -2
  235. data/guides/source/_welcome.html.erb +0 -25
  236. data/guides/source/action_controller_overview.md +0 -1175
  237. data/guides/source/action_mailer_basics.md +0 -689
  238. data/guides/source/action_view_overview.md +0 -1610
  239. data/guides/source/active_model_basics.md +0 -200
  240. data/guides/source/active_record_basics.md +0 -373
  241. data/guides/source/active_record_callbacks.md +0 -410
  242. data/guides/source/active_record_querying.md +0 -1773
  243. data/guides/source/active_record_validations.md +0 -1169
  244. data/guides/source/active_support_core_extensions.md +0 -3864
  245. data/guides/source/active_support_instrumentation.md +0 -496
  246. data/guides/source/api_documentation_guidelines.md +0 -315
  247. data/guides/source/asset_pipeline.md +0 -1163
  248. data/guides/source/association_basics.md +0 -2229
  249. data/guides/source/caching_with_rails.md +0 -354
  250. data/guides/source/command_line.md +0 -603
  251. data/guides/source/configuring.md +0 -942
  252. data/guides/source/contributing_to_ruby_on_rails.md +0 -544
  253. data/guides/source/credits.html.erb +0 -80
  254. data/guides/source/debugging_rails_applications.md +0 -707
  255. data/guides/source/development_dependencies_install.md +0 -278
  256. data/guides/source/documents.yaml +0 -193
  257. data/guides/source/engines.md +0 -1391
  258. data/guides/source/form_helpers.md +0 -1001
  259. data/guides/source/generators.md +0 -663
  260. data/guides/source/getting_started.md +0 -1947
  261. data/guides/source/i18n.md +0 -1043
  262. data/guides/source/index.html.erb +0 -27
  263. data/guides/source/initialization.md +0 -657
  264. data/guides/source/kindle/copyright.html.erb +0 -1
  265. data/guides/source/kindle/layout.html.erb +0 -27
  266. data/guides/source/kindle/rails_guides.opf.erb +0 -52
  267. data/guides/source/kindle/toc.html.erb +0 -24
  268. data/guides/source/kindle/toc.ncx.erb +0 -64
  269. data/guides/source/kindle/welcome.html.erb +0 -5
  270. data/guides/source/layout.html.erb +0 -146
  271. data/guides/source/layouts_and_rendering.md +0 -1226
  272. data/guides/source/maintenance_policy.md +0 -56
  273. data/guides/source/migrations.md +0 -1109
  274. data/guides/source/nested_model_forms.md +0 -225
  275. data/guides/source/plugins.md +0 -444
  276. data/guides/source/rails_application_templates.md +0 -248
  277. data/guides/source/rails_on_rack.md +0 -333
  278. data/guides/source/routing.md +0 -1115
  279. data/guides/source/ruby_on_rails_guides_guidelines.md +0 -128
  280. data/guides/source/security.md +0 -1018
  281. data/guides/source/testing.md +0 -1052
  282. data/guides/source/upgrading_ruby_on_rails.md +0 -899
  283. data/guides/source/working_with_javascript_in_rails.md +0 -405
  284. data/guides/w3c_validator.rb +0 -95
@@ -1,1052 +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. In Rails, you can handle this by defining and customizing fixtures.
53
-
54
- #### What Are Fixtures?
55
-
56
- _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.
57
-
58
- 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.
59
-
60
- #### YAML
61
-
62
- 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`).
63
-
64
- Here's a sample YAML fixture file:
65
-
66
- ```yaml
67
- # lo & behold! I am a YAML comment!
68
- david:
69
- name: David Heinemeier Hansson
70
- birthday: 1979-10-15
71
- profession: Systems development
72
-
73
- steve:
74
- name: Steve Ross Kellock
75
- birthday: 1974-09-27
76
- profession: guy with keyboard
77
- ```
78
-
79
- 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.
80
-
81
- If you are working with [associations](/association_basics.html), you can simply
82
- define a reference node between two different fixtures. Here's an example with
83
- a belongs_to/has_many association:
84
-
85
- ```yaml
86
- # In fixtures/categories.yml
87
- about:
88
- name: About
89
-
90
- # In fixtures/articles.yml
91
- one:
92
- title: Welcome to Rails!
93
- body: Hello world!
94
- category: about
95
- ```
96
-
97
- #### ERB'in It Up
98
-
99
- 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:
100
-
101
- ```erb
102
- <% 1000.times do |n| %>
103
- user_<%= n %>:
104
- username: <%= "user#{n}" %>
105
- email: <%= "user#{n}@example.com" %>
106
- <% end %>
107
- ```
108
-
109
- #### Fixtures in Action
110
-
111
- Rails by default automatically loads all fixtures from the `test/fixtures` folder for your models and controllers test. Loading involves three steps:
112
-
113
- * Remove any existing data from the table corresponding to the fixture
114
- * Load the fixture data into the table
115
- * Dump the fixture data into a variable in case you want to access it directly
116
-
117
- #### Fixtures are Active Record objects
118
-
119
- 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:
120
-
121
- ```ruby
122
- # this will return the User object for the fixture named david
123
- users(:david)
124
-
125
- # this will return the property for david called id
126
- users(:david).id
127
-
128
- # one can also access methods available on the User class
129
- email(david.girlfriend.email, david.location_tonight)
130
- ```
131
-
132
- Unit Testing your Models
133
- ------------------------
134
-
135
- In Rails, models tests are what you write to test your models.
136
-
137
- 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.
138
-
139
- NOTE: For more information on Rails <i>scaffolding</i>, refer to [Getting Started with Rails](getting_started.html)
140
-
141
- When you use `rails generate scaffold`, for a resource among other things it creates a test stub in the `test/models` folder:
142
-
143
- ```bash
144
- $ bin/rails generate scaffold post title:string body:text
145
- ...
146
- create app/models/post.rb
147
- create test/models/post_test.rb
148
- create test/fixtures/posts.yml
149
- ...
150
- ```
151
-
152
- The default test stub in `test/models/post_test.rb` looks like this:
153
-
154
- ```ruby
155
- require 'test_helper'
156
-
157
- class PostTest < ActiveSupport::TestCase
158
- # test "the truth" do
159
- # assert true
160
- # end
161
- end
162
- ```
163
-
164
- A line by line examination of this file will help get you oriented to Rails testing code and terminology.
165
-
166
- ```ruby
167
- require 'test_helper'
168
- ```
169
-
170
- 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.
171
-
172
- ```ruby
173
- class PostTest < ActiveSupport::TestCase
174
- ```
175
-
176
- 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.
177
-
178
- Any method defined within a class inherited from `MiniTest::Unit::TestCase`
179
- (which is the superclass of `ActiveSupport::TestCase`) 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.
180
-
181
- 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,
182
-
183
- ```ruby
184
- test "the truth" do
185
- assert true
186
- end
187
- ```
188
-
189
- acts as if you had written
190
-
191
- ```ruby
192
- def test_the_truth
193
- assert true
194
- end
195
- ```
196
-
197
- only the `test` macro allows a more readable test name. You can still use regular method definitions though.
198
-
199
- 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.
200
-
201
- ```ruby
202
- assert true
203
- ```
204
-
205
- 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:
206
-
207
- * does this value = that value?
208
- * is this object nil?
209
- * does this line of code throw an exception?
210
- * is the user's password greater than 5 characters?
211
-
212
- Every test contains one or more assertions. Only when all the assertions are successful will the test pass.
213
-
214
- ### Maintaining the test database schema
215
-
216
- In order to run your tests, your test database will need to have the current structure. The test helper checks whether your test database has any pending migrations. If so, it will try to load your `db/schema.rb` or `db/structure.sql` into the test database. If migrations are still pending, an error will be raised.
217
-
218
- ### Running Tests
219
-
220
- Running a test is as simple as invoking the file containing the test cases through `rake test` command.
221
-
222
- ```bash
223
- $ bin/rake test test/models/post_test.rb
224
- .
225
-
226
- Finished tests in 0.009262s, 107.9680 tests/s, 107.9680 assertions/s.
227
-
228
- 1 tests, 1 assertions, 0 failures, 0 errors, 0 skips
229
- ```
230
-
231
- You can also run a particular test method from the test case by running the test and providing the `test method name`.
232
-
233
- ```bash
234
- $ bin/rake test test/models/post_test.rb test_the_truth
235
- .
236
-
237
- Finished tests in 0.009064s, 110.3266 tests/s, 110.3266 assertions/s.
238
-
239
- 1 tests, 1 assertions, 0 failures, 0 errors, 0 skips
240
- ```
241
-
242
- 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.
243
-
244
- 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.
245
-
246
- To see how a test failure is reported, you can add a failing test to the `post_test.rb` test case.
247
-
248
- ```ruby
249
- test "should not save post without title" do
250
- post = Post.new
251
- assert_not post.save
252
- end
253
- ```
254
-
255
- Let us run this newly added test.
256
-
257
- ```bash
258
- $ bin/rake test test/models/post_test.rb test_should_not_save_post_without_title
259
- F
260
-
261
- Finished tests in 0.044632s, 22.4054 tests/s, 22.4054 assertions/s.
262
-
263
- 1) Failure:
264
- test_should_not_save_post_without_title(PostTest) [test/models/post_test.rb:6]:
265
- Failed assertion, no message given.
266
-
267
- 1 tests, 1 assertions, 1 failures, 0 errors, 0 skips
268
- ```
269
-
270
- 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:
271
-
272
- ```ruby
273
- test "should not save post without title" do
274
- post = Post.new
275
- assert_not post.save, "Saved the post without a title"
276
- end
277
- ```
278
-
279
- Running this test shows the friendlier assertion message:
280
-
281
- ```bash
282
- 1) Failure:
283
- test_should_not_save_post_without_title(PostTest) [test/models/post_test.rb:6]:
284
- Saved the post without a title
285
- ```
286
-
287
- Now to get this test to pass we can add a model level validation for the _title_ field.
288
-
289
- ```ruby
290
- class Post < ActiveRecord::Base
291
- validates :title, presence: true
292
- end
293
- ```
294
-
295
- Now the test should pass. Let us verify by running the test again:
296
-
297
- ```bash
298
- $ bin/rake test test/models/post_test.rb test_should_not_save_post_without_title
299
- .
300
-
301
- Finished tests in 0.047721s, 20.9551 tests/s, 20.9551 assertions/s.
302
-
303
- 1 tests, 1 assertions, 0 failures, 0 errors, 0 skips
304
- ```
305
-
306
- 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).
307
-
308
- 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).
309
-
310
- To see how an error gets reported, here's a test containing an error:
311
-
312
- ```ruby
313
- test "should report error" do
314
- # some_undefined_variable is not defined elsewhere in the test case
315
- some_undefined_variable
316
- assert true
317
- end
318
- ```
319
-
320
- Now you can see even more output in the console from running the tests:
321
-
322
- ```bash
323
- $ bin/rake test test/models/post_test.rb test_should_report_error
324
- E
325
-
326
- Finished tests in 0.030974s, 32.2851 tests/s, 0.0000 assertions/s.
327
-
328
- 1) Error:
329
- test_should_report_error(PostTest):
330
- NameError: undefined local variable or method `some_undefined_variable' for #<PostTest:0x007fe32e24afe0>
331
- test/models/post_test.rb:10:in `block in <class:PostTest>'
332
-
333
- 1 tests, 0 assertions, 0 failures, 1 errors, 0 skips
334
- ```
335
-
336
- Notice the 'E' in the output. It denotes a test with error.
337
-
338
- 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.
339
-
340
- When a test fails you are presented with the corresponding backtrace. By default
341
- Rails filters that backtrace and will only print lines relevant to your
342
- application. This eliminates the framework noise and helps to focus on your
343
- code. However there are situations when you want to see the full
344
- backtrace. simply set the `BACKTRACE` environment variable to enable this
345
- behavior:
346
-
347
- ```bash
348
- $ BACKTRACE=1 bin/rake test test/models/post_test.rb
349
- ```
350
-
351
- ### What to Include in Your Unit Tests
352
-
353
- 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.
354
-
355
- ### Available Assertions
356
-
357
- 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.
358
-
359
- There are a bunch of different types of assertions you can use.
360
- Here's an extract of the assertions you can use with `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.
361
-
362
- | Assertion | Purpose |
363
- | ---------------------------------------------------------------- | ------- |
364
- | `assert( test, [msg] )` | Ensures that `test` is true.|
365
- | `assert_not( test, [msg] )` | Ensures that `test` is false.|
366
- | `assert_equal( expected, actual, [msg] )` | Ensures that `expected == actual` is true.|
367
- | `assert_not_equal( expected, actual, [msg] )` | Ensures that `expected != actual` is true.|
368
- | `assert_same( expected, actual, [msg] )` | Ensures that `expected.equal?(actual)` is true.|
369
- | `assert_not_same( expected, actual, [msg] )` | Ensures that `expected.equal?(actual)` is false.|
370
- | `assert_nil( obj, [msg] )` | Ensures that `obj.nil?` is true.|
371
- | `assert_not_nil( obj, [msg] )` | Ensures that `obj.nil?` is false.|
372
- | `assert_match( regexp, string, [msg] )` | Ensures that a string matches the regular expression.|
373
- | `assert_no_match( regexp, string, [msg] )` | Ensures that a string doesn't match the regular expression.|
374
- | `assert_in_delta( expecting, actual, [delta], [msg] )` | Ensures that the numbers `expected` and `actual` are within `delta` of each other.|
375
- | `assert_not_in_delta( expecting, actual, [delta], [msg] )` | Ensures that the numbers `expected` and `actual` are not within `delta` of each other.|
376
- | `assert_throws( symbol, [msg] ) { block }` | Ensures that the given block throws the symbol.|
377
- | `assert_raises( exception1, exception2, ... ) { block }` | Ensures that the given block raises one of the given exceptions.|
378
- | `assert_nothing_raised( exception1, exception2, ... ) { block }` | Ensures that the given block doesn't raise one of the given exceptions.|
379
- | `assert_instance_of( class, obj, [msg] )` | Ensures that `obj` is an instance of `class`.|
380
- | `assert_not_instance_of( class, obj, [msg] )` | Ensures that `obj` is not an instance of `class`.|
381
- | `assert_kind_of( class, obj, [msg] )` | Ensures that `obj` is or descends from `class`.|
382
- | `assert_not_kind_of( class, obj, [msg] )` | Ensures that `obj` is not an instance of `class` and is not descending from it.|
383
- | `assert_respond_to( obj, symbol, [msg] )` | Ensures that `obj` responds to `symbol`.|
384
- | `assert_not_respond_to( obj, symbol, [msg] )` | Ensures that `obj` does not respond to `symbol`.|
385
- | `assert_operator( obj1, operator, [obj2], [msg] )` | Ensures that `obj1.operator(obj2)` is true.|
386
- | `assert_not_operator( obj1, operator, [obj2], [msg] )` | Ensures that `obj1.operator(obj2)` is false.|
387
- | `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?|
388
- | `flunk( [msg] )` | Ensures failure. This is useful to explicitly mark a test that isn't finished yet.|
389
-
390
- 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.
391
-
392
- NOTE: Creating your own assertions is an advanced topic that we won't cover in this tutorial.
393
-
394
- ### Rails Specific Assertions
395
-
396
- Rails adds some custom assertions of its own to the `test/unit` framework:
397
-
398
- | Assertion | Purpose |
399
- | --------------------------------------------------------------------------------- | ------- |
400
- | `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.|
401
- | `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.|
402
- | `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.|
403
- | `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.|
404
- | `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.|
405
- | `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`.|
406
- | `assert_template(expected = nil, message=nil)` | Asserts that the request was rendered with the appropriate template file.|
407
-
408
- You'll see the usage of some of these assertions in the next chapter.
409
-
410
- Functional Tests for Your Controllers
411
- -------------------------------------
412
-
413
- 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.
414
-
415
- ### What to Include in your Functional Tests
416
-
417
- You should test for things such as:
418
-
419
- * was the web request successful?
420
- * was the user redirected to the right page?
421
- * was the user successfully authenticated?
422
- * was the correct object stored in the response template?
423
- * was the appropriate message displayed to the user in the view?
424
-
425
- 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.
426
-
427
- Let me take you through one such test, `test_should_get_index` from the file `posts_controller_test.rb`.
428
-
429
- ```ruby
430
- class PostsControllerTest < ActionController::TestCase
431
- test "should get index" do
432
- get :index
433
- assert_response :success
434
- assert_not_nil assigns(:posts)
435
- end
436
- end
437
- ```
438
-
439
- 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.
440
-
441
- The `get` method kicks off the web request and populates the results into the response. It accepts 4 arguments:
442
-
443
- * The action of the controller you are requesting. This can be in the form of a string or a symbol.
444
- * An optional hash of request parameters to pass into the action (eg. query string parameters or post variables).
445
- * An optional hash of session variables to pass along with the request.
446
- * An optional hash of flash values.
447
-
448
- Example: Calling the `:show` action, passing an `id` of 12 as the `params` and setting a `user_id` of 5 in the session:
449
-
450
- ```ruby
451
- get(:show, {'id' => "12"}, {'user_id' => 5})
452
- ```
453
-
454
- Another example: Calling the `:view` action, passing an `id` of 12 as the `params`, this time with no session, but with a flash message.
455
-
456
- ```ruby
457
- get(:view, {'id' => '12'}, nil, {'message' => 'booya!'})
458
- ```
459
-
460
- 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.
461
-
462
- Let us modify `test_should_create_post` test in `posts_controller_test.rb` so that all our test pass:
463
-
464
- ```ruby
465
- test "should create post" do
466
- assert_difference('Post.count') do
467
- post :create, post: {title: 'Some title'}
468
- end
469
-
470
- assert_redirected_to post_path(assigns(:post))
471
- end
472
- ```
473
-
474
- Now you can try running all the tests and they should pass.
475
-
476
- ### Available Request Types for Functional Tests
477
-
478
- 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:
479
-
480
- * `get`
481
- * `post`
482
- * `patch`
483
- * `put`
484
- * `head`
485
- * `delete`
486
-
487
- 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.
488
-
489
- 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.
490
-
491
- ### The Four Hashes of the Apocalypse
492
-
493
- 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:
494
-
495
- * `assigns` - Any objects that are stored as instance variables in actions for use in views.
496
- * `cookies` - Any cookies that are set.
497
- * `flash` - Any objects living in the flash.
498
- * `session` - Any object living in session variables.
499
-
500
- 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:
501
-
502
- ```ruby
503
- flash["gordon"] flash[:gordon]
504
- session["shmession"] session[:shmession]
505
- cookies["are_good_for_u"] cookies[:are_good_for_u]
506
-
507
- # Because you can't use assigns[:something] for historical reasons:
508
- assigns["something"] assigns(:something)
509
- ```
510
-
511
- ### Instance Variables Available
512
-
513
- You also have access to three instance variables in your functional tests:
514
-
515
- * `@controller` - The controller processing the request
516
- * `@request` - The request
517
- * `@response` - The response
518
-
519
- ### Setting Headers and CGI variables
520
-
521
- [HTTP headers](http://tools.ietf.org/search/rfc2616#section-5.3)
522
- and
523
- [CGI variables](http://tools.ietf.org/search/rfc3875#section-4.1)
524
- can be set directly on the `@request` instance variable:
525
-
526
- ```ruby
527
- # setting a HTTP Header
528
- @request.headers["Accept"] = "text/plain, text/html"
529
- get :index # simulate the request with custom header
530
-
531
- # setting a CGI variable
532
- @request.headers["HTTP_REFERER"] = "http://example.com/home"
533
- post :create # simulate the request with custom env variable
534
- ```
535
-
536
- ### Testing Templates and Layouts
537
-
538
- If you want to make sure that the response rendered the correct template and layout, you can use the `assert_template`
539
- method:
540
-
541
- ```ruby
542
- test "index should render correct template and layout" do
543
- get :index
544
- assert_template :index
545
- assert_template layout: "layouts/application"
546
- end
547
- ```
548
-
549
- Note that you cannot test for template and layout at the same time, with one call to `assert_template` method.
550
- Also, for the `layout` test, you can give a regular expression instead of a string, but using the string, makes
551
- things clearer. On the other hand, you have to include the "layouts" directory name even if you save your layout
552
- file in this standard layout directory. Hence,
553
-
554
- ```ruby
555
- assert_template layout: "application"
556
- ```
557
-
558
- will not work.
559
-
560
- If your view renders any partial, when asserting for the layout, you have to assert for the partial at the same time.
561
- Otherwise, assertion will fail.
562
-
563
- Hence:
564
-
565
- ```ruby
566
- test "new should render correct layout" do
567
- get :new
568
- assert_template layout: "layouts/application", partial: "_form"
569
- end
570
- ```
571
-
572
- 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.
573
-
574
- ### A Fuller Functional Test Example
575
-
576
- Here's another example that uses `flash`, `assert_redirected_to`, and `assert_difference`:
577
-
578
- ```ruby
579
- test "should create post" do
580
- assert_difference('Post.count') do
581
- post :create, post: {title: 'Hi', body: 'This is my first post.'}
582
- end
583
- assert_redirected_to post_path(assigns(:post))
584
- assert_equal 'Post was successfully created.', flash[:notice]
585
- end
586
- ```
587
-
588
- ### Testing Views
589
-
590
- 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.
591
-
592
- NOTE: You may find references to `assert_tag` in other documentation, but this is now deprecated in favor of `assert_select`.
593
-
594
- There are two forms of `assert_select`:
595
-
596
- `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.
597
-
598
- `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.
599
-
600
- For example, you could verify the contents on the title element in your response with:
601
-
602
- ```ruby
603
- assert_select 'title', "Welcome to Rails Testing Guide"
604
- ```
605
-
606
- 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:
607
-
608
- ```ruby
609
- assert_select 'ul.navigation' do
610
- assert_select 'li.menu_item'
611
- end
612
- ```
613
-
614
- 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.
615
-
616
- ```ruby
617
- assert_select "ol" do |elements|
618
- elements.each do |element|
619
- assert_select element, "li", 4
620
- end
621
- end
622
-
623
- assert_select "ol" do
624
- assert_select "li", 8
625
- end
626
- ```
627
-
628
- The `assert_select` assertion is quite powerful. For more advanced usage, refer to its [documentation](http://api.rubyonrails.org/classes/ActionDispatch/Assertions/SelectorAssertions.html).
629
-
630
- #### Additional View-Based Assertions
631
-
632
- There are more assertions that are primarily used in testing views:
633
-
634
- | Assertion | Purpose |
635
- | --------------------------------------------------------- | ------- |
636
- | `assert_select_email` | Allows you to make assertions on the body of an e-mail. |
637
- | `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.|
638
- | `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.|
639
-
640
- Here's an example of using `assert_select_email`:
641
-
642
- ```ruby
643
- assert_select_email do
644
- assert_select 'small', 'Please click the "Unsubscribe" link if you want to opt-out.'
645
- end
646
- ```
647
-
648
- Integration Testing
649
- -------------------
650
-
651
- 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.
652
-
653
- 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.
654
-
655
- ```bash
656
- $ bin/rails generate integration_test user_flows
657
- exists test/integration/
658
- create test/integration/user_flows_test.rb
659
- ```
660
-
661
- Here's what a freshly-generated integration test looks like:
662
-
663
- ```ruby
664
- require 'test_helper'
665
-
666
- class UserFlowsTest < ActionDispatch::IntegrationTest
667
- # test "the truth" do
668
- # assert true
669
- # end
670
- end
671
- ```
672
-
673
- 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.
674
-
675
- ### Helpers Available for Integration Tests
676
-
677
- In addition to the standard testing helpers, there are some additional helpers available to integration tests:
678
-
679
- | Helper | Purpose |
680
- | ------------------------------------------------------------------ | ------- |
681
- | `https?` | Returns `true` if the session is mimicking a secure HTTPS request.|
682
- | `https!` | Allows you to mimic a secure HTTPS request.|
683
- | `host!` | Allows you to set the host name to use in the next request.|
684
- | `redirect?` | Returns `true` if the last request was a redirect.|
685
- | `follow_redirect!` | Follows a single redirect response.|
686
- | `request_via_redirect(http_method, path, [parameters], [headers])` | Allows you to make an HTTP request and follow any subsequent redirects.|
687
- | `post_via_redirect(path, [parameters], [headers])` | Allows you to make an HTTP POST request and follow any subsequent redirects.|
688
- | `get_via_redirect(path, [parameters], [headers])` | Allows you to make an HTTP GET request and follow any subsequent redirects.|
689
- | `patch_via_redirect(path, [parameters], [headers])` | Allows you to make an HTTP PATCH request and follow any subsequent redirects.|
690
- | `put_via_redirect(path, [parameters], [headers])` | Allows you to make an HTTP PUT request and follow any subsequent redirects.|
691
- | `delete_via_redirect(path, [parameters], [headers])` | Allows you to make an HTTP DELETE request and follow any subsequent redirects.|
692
- | `open_session` | Opens a new session instance.|
693
-
694
- ### Integration Testing Examples
695
-
696
- A simple integration test that exercises multiple controllers:
697
-
698
- ```ruby
699
- require 'test_helper'
700
-
701
- class UserFlowsTest < ActionDispatch::IntegrationTest
702
- test "login and browse site" do
703
- # login via https
704
- https!
705
- get "/login"
706
- assert_response :success
707
-
708
- post_via_redirect "/login", username: users(:david).username, password: users(:david).password
709
- assert_equal '/welcome', path
710
- assert_equal 'Welcome david!', flash[:notice]
711
-
712
- https!(false)
713
- get "/posts/all"
714
- assert_response :success
715
- assert assigns(:products)
716
- end
717
- end
718
- ```
719
-
720
- 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.
721
-
722
- Here's an example of multiple sessions and custom DSL in an integration test
723
-
724
- ```ruby
725
- require 'test_helper'
726
-
727
- class UserFlowsTest < ActionDispatch::IntegrationTest
728
- test "login and browse site" do
729
- # User david logs in
730
- david = login(:david)
731
- # User guest logs in
732
- guest = login(:guest)
733
-
734
- # Both are now available in different sessions
735
- assert_equal 'Welcome david!', david.flash[:notice]
736
- assert_equal 'Welcome guest!', guest.flash[:notice]
737
-
738
- # User david can browse site
739
- david.browses_site
740
- # User guest can browse site as well
741
- guest.browses_site
742
-
743
- # Continue with other assertions
744
- end
745
-
746
- private
747
-
748
- module CustomDsl
749
- def browses_site
750
- get "/products/all"
751
- assert_response :success
752
- assert assigns(:products)
753
- end
754
- end
755
-
756
- def login(user)
757
- open_session do |sess|
758
- sess.extend(CustomDsl)
759
- u = users(user)
760
- sess.https!
761
- sess.post "/login", username: u.username, password: u.password
762
- assert_equal '/welcome', sess.path
763
- sess.https!(false)
764
- end
765
- end
766
- end
767
- ```
768
-
769
- Rake Tasks for Running your Tests
770
- ---------------------------------
771
-
772
- You don't need to set up and run your tests by hand on a test-by-test basis.
773
- Rails comes with a number of commands to help in testing.
774
- The table below lists all commands that come along in the default Rakefile
775
- when you initiate a Rails project.
776
-
777
- | Tasks | Description |
778
- | ----------------------- | ----------- |
779
- | `rake test` | Runs all unit, functional and integration tests. You can also simply run `rake` as Rails will run all the tests by default |
780
- | `rake test:controllers` | Runs all the controller tests from `test/controllers` |
781
- | `rake test:functionals` | Runs all the functional tests from `test/controllers`, `test/mailers`, and `test/functional` |
782
- | `rake test:helpers` | Runs all the helper tests from `test/helpers` |
783
- | `rake test:integration` | Runs all the integration tests from `test/integration` |
784
- | `rake test:mailers` | Runs all the mailer tests from `test/mailers` |
785
- | `rake test:models` | Runs all the model tests from `test/models` |
786
- | `rake test:units` | Runs all the unit tests from `test/models`, `test/helpers`, and `test/unit` |
787
- | `rake test:all` | Runs all tests quickly by merging all types and not resetting db |
788
- | `rake test:all:db` | Runs all tests quickly by merging all types and resetting db |
789
-
790
-
791
- Brief Note About `MiniTest`
792
- -----------------------------
793
-
794
- 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
795
- us to use all of the basic assertions in our tests.
796
-
797
- 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.
798
-
799
- NOTE: For more information on `Test::Unit`, refer to [test/unit Documentation](http://ruby-doc.org/stdlib/libdoc/test/unit/rdoc/)
800
- For more information on `MiniTest`, refer to [Minitest](http://www.ruby-doc.org/stdlib-1.9.3/libdoc/minitest/unit/rdoc/)
801
-
802
- Setup and Teardown
803
- ------------------
804
-
805
- 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:
806
-
807
- ```ruby
808
- require 'test_helper'
809
-
810
- class PostsControllerTest < ActionController::TestCase
811
-
812
- # called before every single test
813
- def setup
814
- @post = posts(:one)
815
- end
816
-
817
- # called after every single test
818
- def teardown
819
- # as we are re-initializing @post before every test
820
- # setting it to nil here is not essential but I hope
821
- # you understand how you can use the teardown method
822
- @post = nil
823
- end
824
-
825
- test "should show post" do
826
- get :show, id: @post.id
827
- assert_response :success
828
- end
829
-
830
- test "should destroy post" do
831
- assert_difference('Post.count', -1) do
832
- delete :destroy, id: @post.id
833
- end
834
-
835
- assert_redirected_to posts_path
836
- end
837
-
838
- end
839
- ```
840
-
841
- 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:
842
-
843
- * a block
844
- * a method (like in the earlier example)
845
- * a method name as a symbol
846
- * a lambda
847
-
848
- Let's see the earlier example by specifying `setup` callback by specifying a method name as a symbol:
849
-
850
- ```ruby
851
- require 'test_helper'
852
-
853
- class PostsControllerTest < ActionController::TestCase
854
-
855
- # called before every single test
856
- setup :initialize_post
857
-
858
- # called after every single test
859
- def teardown
860
- @post = nil
861
- end
862
-
863
- test "should show post" do
864
- get :show, id: @post.id
865
- assert_response :success
866
- end
867
-
868
- test "should update post" do
869
- patch :update, id: @post.id, post: {}
870
- assert_redirected_to post_path(assigns(:post))
871
- end
872
-
873
- test "should destroy post" do
874
- assert_difference('Post.count', -1) do
875
- delete :destroy, id: @post.id
876
- end
877
-
878
- assert_redirected_to posts_path
879
- end
880
-
881
- private
882
-
883
- def initialize_post
884
- @post = posts(:one)
885
- end
886
- end
887
- ```
888
-
889
- Testing Routes
890
- --------------
891
-
892
- 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:
893
-
894
- ```ruby
895
- test "should route to post" do
896
- assert_routing '/posts/1', {controller: "posts", action: "show", id: "1"}
897
- end
898
- ```
899
-
900
- Testing Your Mailers
901
- --------------------
902
-
903
- Testing mailer classes requires some specific tools to do a thorough job.
904
-
905
- ### Keeping the Postman in Check
906
-
907
- Your mailer classes - like every other part of your Rails application - should be tested to ensure that it is working as expected.
908
-
909
- The goals of testing your mailer classes are to ensure that:
910
-
911
- * emails are being processed (created and sent)
912
- * the email content is correct (subject, sender, body, etc)
913
- * the right emails are being sent at the right times
914
-
915
- #### From All Sides
916
-
917
- 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.
918
-
919
- ### Unit Testing
920
-
921
- 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.
922
-
923
- #### Revenge of the Fixtures
924
-
925
- 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.
926
-
927
- 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.
928
-
929
- #### The Basic Test Case
930
-
931
- 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.
932
-
933
- ```ruby
934
- require 'test_helper'
935
-
936
- class UserMailerTest < ActionMailer::TestCase
937
- test "invite" do
938
- # Send the email, then test that it got queued
939
- email = UserMailer.create_invite('me@example.com',
940
- 'friend@example.com', Time.now).deliver
941
- assert_not ActionMailer::Base.deliveries.empty?
942
-
943
- # Test the body of the sent email contains what we expect it to
944
- assert_equal ['me@example.com'], email.from
945
- assert_equal ['friend@example.com'], email.to
946
- assert_equal 'You have been invited by me@example.com', email.subject
947
- assert_equal read_fixture('invite').join, email.body.to_s
948
- end
949
- end
950
- ```
951
-
952
- In the test we send the email and store the returned object in the `email`
953
- variable. We then ensure that it was sent (the first assert), then, in the
954
- second batch of assertions, we ensure that the email does indeed contain what we
955
- expect. The helper `read_fixture` is used to read in the content from this file.
956
-
957
- Here's the content of the `invite` fixture:
958
-
959
- ```
960
- Hi friend@example.com,
961
-
962
- You have been invited.
963
-
964
- Cheers!
965
- ```
966
-
967
- This is the right time to understand a little more about writing tests for your
968
- mailers. The line `ActionMailer::Base.delivery_method = :test` in
969
- `config/environments/test.rb` sets the delivery method to test mode so that
970
- email will not actually be delivered (useful to avoid spamming your users while
971
- testing) but instead it will be appended to an array
972
- (`ActionMailer::Base.deliveries`).
973
-
974
- NOTE: The `ActionMailer::Base.deliveries` array is only reset automatically in
975
- `ActionMailer::TestCase` tests. If you want to have a clean slate outside Action
976
- Mailer tests, you can reset it manually with:
977
- `ActionMailer::Base.deliveries.clear`
978
-
979
- ### Functional Testing
980
-
981
- 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:
982
-
983
- ```ruby
984
- require 'test_helper'
985
-
986
- class UserControllerTest < ActionController::TestCase
987
- test "invite friend" do
988
- assert_difference 'ActionMailer::Base.deliveries.size', +1 do
989
- post :invite_friend, email: 'friend@example.com'
990
- end
991
- invite_email = ActionMailer::Base.deliveries.last
992
-
993
- assert_equal "You have been invited by me@example.com", invite_email.subject
994
- assert_equal 'friend@example.com', invite_email.to[0]
995
- assert_match(/Hi friend@example.com/, invite_email.body)
996
- end
997
- end
998
- ```
999
-
1000
- Testing helpers
1001
- ---------------
1002
-
1003
- In order to test helpers, all you need to do is check that the output of the
1004
- helper method matches what you'd expect. Tests related to the helpers are
1005
- located under the `test/helpers` directory. Rails provides a generator which
1006
- generates both the helper and the test file:
1007
-
1008
- ```bash
1009
- $ bin/rails generate helper User
1010
- create app/helpers/user_helper.rb
1011
- invoke test_unit
1012
- create test/helpers/user_helper_test.rb
1013
- ```
1014
-
1015
- The generated test file contains the following code:
1016
-
1017
- ```ruby
1018
- require 'test_helper'
1019
-
1020
- class UserHelperTest < ActionView::TestCase
1021
- end
1022
- ```
1023
-
1024
- A helper is just a simple module where you can define methods which are
1025
- available into your views. To test the output of the helper's methods, you just
1026
- have to use a mixin like this:
1027
-
1028
- ```ruby
1029
- class UserHelperTest < ActionView::TestCase
1030
- include UserHelper
1031
-
1032
- test "should return the user name" do
1033
- # ...
1034
- end
1035
- end
1036
- ```
1037
-
1038
- Moreover, since the test class extends from `ActionView::TestCase`, you have
1039
- access to Rails' helper methods such as `link_to` or `pluralize`.
1040
-
1041
- Other Testing Approaches
1042
- ------------------------
1043
-
1044
- 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:
1045
-
1046
- * [NullDB](http://avdi.org/projects/nulldb/), a way to speed up testing by avoiding database use.
1047
- * [Factory Girl](https://github.com/thoughtbot/factory_girl/tree/master), a replacement for fixtures.
1048
- * [Machinist](https://github.com/notahat/machinist/tree/master), another replacement for fixtures.
1049
- * [Fixture Builder](https://github.com/rdy/fixture_builder), a tool that compiles Ruby factories into fixtures before a test run.
1050
- * [MiniTest::Spec Rails](https://github.com/metaskills/minitest-spec-rails), use the MiniTest::Spec DSL within your rails tests.
1051
- * [Shoulda](http://www.thoughtbot.com/projects/shoulda), an extension to `test/unit` with additional helpers, macros, and assertions.
1052
- * [RSpec](http://relishapp.com/rspec), a behavior-driven development framework