rails 2.2.3 → 2.3.2

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 (229) hide show
  1. data/CHANGELOG +272 -191
  2. data/MIT-LICENSE +1 -1
  3. data/README +6 -19
  4. data/Rakefile +24 -71
  5. data/bin/rails +1 -0
  6. data/builtin/rails_info/rails/info.rb +12 -8
  7. data/configs/databases/mysql.yml +3 -0
  8. data/configs/initializers/backtrace_silencers.rb +7 -0
  9. data/configs/initializers/new_rails_defaults.rb +2 -0
  10. data/configs/initializers/session_store.rb +15 -0
  11. data/dispatches/config.ru +7 -0
  12. data/doc/README_FOR_APP +2 -5
  13. data/environments/boot.rb +1 -0
  14. data/environments/environment.rb +14 -48
  15. data/environments/production.rb +11 -7
  16. data/environments/test.rb +6 -0
  17. data/helpers/application_controller.rb +10 -0
  18. data/helpers/test_helper.rb +1 -1
  19. data/html/500.html +0 -3
  20. data/html/index.html +1 -0
  21. data/lib/commands/about.rb +1 -1
  22. data/lib/commands/dbconsole.rb +18 -2
  23. data/lib/commands/plugin.rb +4 -3
  24. data/lib/commands/runner.rb +13 -7
  25. data/lib/commands/server.rb +98 -33
  26. data/lib/console_app.rb +4 -4
  27. data/lib/console_with_helpers.rb +2 -23
  28. data/lib/dispatcher.rb +1 -1
  29. data/lib/fcgi_handler.rb +12 -10
  30. data/lib/initializer.rb +108 -41
  31. data/lib/rails/backtrace_cleaner.rb +54 -0
  32. data/lib/rails/gem_dependency.rb +124 -94
  33. data/lib/rails/plugin.rb +49 -6
  34. data/lib/rails/plugin/loader.rb +66 -27
  35. data/lib/rails/plugin/locator.rb +1 -1
  36. data/lib/rails/rack.rb +3 -1
  37. data/lib/rails/rack/debugger.rb +21 -0
  38. data/lib/rails/rack/log_tailer.rb +35 -0
  39. data/lib/rails/rack/metal.rb +51 -0
  40. data/lib/rails/rack/static.rb +15 -4
  41. data/lib/rails/version.rb +2 -2
  42. data/lib/rails_generator/base.rb +3 -0
  43. data/lib/rails_generator/commands.rb +8 -3
  44. data/lib/rails_generator/generators/applications/app/app_generator.rb +210 -136
  45. data/lib/rails_generator/generators/applications/app/scm/git.rb +16 -0
  46. data/lib/rails_generator/generators/applications/app/scm/scm.rb +8 -0
  47. data/lib/rails_generator/generators/applications/app/scm/svn.rb +7 -0
  48. data/lib/rails_generator/generators/applications/app/template_runner.rb +401 -0
  49. data/lib/rails_generator/generators/components/controller/USAGE +12 -11
  50. data/lib/rails_generator/generators/components/controller/controller_generator.rb +7 -1
  51. data/lib/rails_generator/generators/components/controller/templates/helper_test.rb +4 -0
  52. data/lib/rails_generator/generators/components/helper/USAGE +24 -0
  53. data/lib/rails_generator/generators/components/helper/helper_generator.rb +25 -0
  54. data/lib/rails_generator/generators/components/helper/templates/helper.rb +2 -0
  55. data/lib/rails_generator/generators/components/helper/templates/helper_test.rb +4 -0
  56. data/lib/rails_generator/generators/components/metal/USAGE +8 -0
  57. data/lib/rails_generator/generators/components/metal/metal_generator.rb +8 -0
  58. data/lib/rails_generator/generators/components/metal/templates/metal.rb +12 -0
  59. data/lib/rails_generator/generators/components/resource/USAGE +2 -2
  60. data/lib/rails_generator/generators/components/resource/resource_generator.rb +2 -0
  61. data/lib/rails_generator/generators/components/resource/templates/helper_test.rb +4 -0
  62. data/lib/rails_generator/generators/components/scaffold/scaffold_generator.rb +2 -0
  63. data/lib/rails_generator/generators/components/scaffold/templates/controller.rb +1 -1
  64. data/lib/rails_generator/generators/components/scaffold/templates/functional_test.rb +4 -4
  65. data/lib/rails_generator/generators/components/scaffold/templates/helper_test.rb +4 -0
  66. data/lib/rails_generator/generators/components/scaffold/templates/layout.html.erb +1 -1
  67. data/lib/rails_generator/generators/components/scaffold/templates/view_edit.html.erb +2 -2
  68. data/lib/rails_generator/generators/components/scaffold/templates/view_index.html.erb +2 -2
  69. data/lib/rails_generator/generators/components/scaffold/templates/view_new.html.erb +2 -2
  70. data/lib/rails_generator/generators/components/scaffold/templates/view_show.html.erb +1 -1
  71. data/lib/rails_generator/secret_key_generator.rb +2 -0
  72. data/lib/tasks/databases.rake +13 -6
  73. data/lib/tasks/documentation.rake +2 -9
  74. data/lib/tasks/framework.rake +26 -1
  75. data/lib/tasks/gems.rake +33 -48
  76. data/lib/tasks/middleware.rake +7 -0
  77. data/lib/tasks/misc.rake +7 -0
  78. data/lib/tasks/statistics.rake +0 -1
  79. data/lib/tasks/testing.rake +5 -5
  80. data/lib/tasks/tmp.rake +2 -2
  81. data/lib/test_help.rb +16 -8
  82. metadata +92 -159
  83. data/bin/performance/request +0 -3
  84. data/bin/process/inspector +0 -3
  85. data/bin/process/reaper +0 -3
  86. data/bin/process/spawner +0 -3
  87. data/config.ru +0 -17
  88. data/configs/apache.conf +0 -40
  89. data/configs/lighttpd.conf +0 -54
  90. data/doc/guides/html/2_2_release_notes.html +0 -1185
  91. data/doc/guides/html/actioncontroller_basics.html +0 -1270
  92. data/doc/guides/html/activerecord_validations_callbacks.html +0 -749
  93. data/doc/guides/html/association_basics.html +0 -2585
  94. data/doc/guides/html/authors.html +0 -240
  95. data/doc/guides/html/benchmarking_and_profiling.html +0 -1018
  96. data/doc/guides/html/caching_with_rails.html +0 -583
  97. data/doc/guides/html/command_line.html +0 -434
  98. data/doc/guides/html/configuring.html +0 -438
  99. data/doc/guides/html/creating_plugins.html +0 -1594
  100. data/doc/guides/html/debugging_rails_applications.html +0 -1175
  101. data/doc/guides/html/finders.html +0 -1090
  102. data/doc/guides/html/form_helpers.html +0 -638
  103. data/doc/guides/html/getting_started_with_rails.html +0 -2066
  104. data/doc/guides/html/index.html +0 -349
  105. data/doc/guides/html/layouts_and_rendering.html +0 -1406
  106. data/doc/guides/html/migrations.html +0 -921
  107. data/doc/guides/html/routing_outside_in.html +0 -2213
  108. data/doc/guides/html/security.html +0 -1346
  109. data/doc/guides/html/testing_rails_applications.html +0 -1859
  110. data/doc/guides/source/2_2_release_notes.txt +0 -435
  111. data/doc/guides/source/actioncontroller_basics/changelog.txt +0 -5
  112. data/doc/guides/source/actioncontroller_basics/cookies.txt +0 -34
  113. data/doc/guides/source/actioncontroller_basics/csrf.txt +0 -32
  114. data/doc/guides/source/actioncontroller_basics/filters.txt +0 -119
  115. data/doc/guides/source/actioncontroller_basics/http_auth.txt +0 -24
  116. data/doc/guides/source/actioncontroller_basics/index.txt +0 -40
  117. data/doc/guides/source/actioncontroller_basics/introduction.txt +0 -9
  118. data/doc/guides/source/actioncontroller_basics/methods.txt +0 -39
  119. data/doc/guides/source/actioncontroller_basics/parameter_filtering.txt +0 -14
  120. data/doc/guides/source/actioncontroller_basics/params.txt +0 -93
  121. data/doc/guides/source/actioncontroller_basics/request_response_objects.txt +0 -43
  122. data/doc/guides/source/actioncontroller_basics/rescue.txt +0 -67
  123. data/doc/guides/source/actioncontroller_basics/session.txt +0 -187
  124. data/doc/guides/source/actioncontroller_basics/streaming.txt +0 -91
  125. data/doc/guides/source/actioncontroller_basics/verification.txt +0 -40
  126. data/doc/guides/source/active_record_basics.txt +0 -181
  127. data/doc/guides/source/activerecord_validations_callbacks.txt +0 -404
  128. data/doc/guides/source/association_basics.txt +0 -1840
  129. data/doc/guides/source/authors.txt +0 -39
  130. data/doc/guides/source/benchmarking_and_profiling/appendix.txt +0 -95
  131. data/doc/guides/source/benchmarking_and_profiling/digging_deeper.txt +0 -105
  132. data/doc/guides/source/benchmarking_and_profiling/edge_rails_features.txt +0 -185
  133. data/doc/guides/source/benchmarking_and_profiling/gameplan.txt +0 -27
  134. data/doc/guides/source/benchmarking_and_profiling/index.txt +0 -242
  135. data/doc/guides/source/benchmarking_and_profiling/rubyprof.txt +0 -179
  136. data/doc/guides/source/benchmarking_and_profiling/statistics.txt +0 -57
  137. data/doc/guides/source/caching_with_rails.txt +0 -367
  138. data/doc/guides/source/command_line.txt +0 -147
  139. data/doc/guides/source/configuring.txt +0 -225
  140. data/doc/guides/source/creating_plugins/acts_as_yaffle.txt +0 -191
  141. data/doc/guides/source/creating_plugins/appendix.txt +0 -46
  142. data/doc/guides/source/creating_plugins/controllers.txt +0 -59
  143. data/doc/guides/source/creating_plugins/core_ext.txt +0 -123
  144. data/doc/guides/source/creating_plugins/custom_route.txt +0 -69
  145. data/doc/guides/source/creating_plugins/gem.txt +0 -1
  146. data/doc/guides/source/creating_plugins/generator_method.txt +0 -89
  147. data/doc/guides/source/creating_plugins/helpers.txt +0 -51
  148. data/doc/guides/source/creating_plugins/index.txt +0 -52
  149. data/doc/guides/source/creating_plugins/migration_generator.txt +0 -156
  150. data/doc/guides/source/creating_plugins/models.txt +0 -76
  151. data/doc/guides/source/creating_plugins/odds_and_ends.txt +0 -69
  152. data/doc/guides/source/creating_plugins/test_setup.txt +0 -230
  153. data/doc/guides/source/debugging_rails_applications.txt +0 -733
  154. data/doc/guides/source/finders.txt +0 -668
  155. data/doc/guides/source/form_helpers.txt +0 -345
  156. data/doc/guides/source/getting_started_with_rails.txt +0 -1256
  157. data/doc/guides/source/images/belongs_to.png +0 -0
  158. data/doc/guides/source/images/bullet.gif +0 -0
  159. data/doc/guides/source/images/csrf.png +0 -0
  160. data/doc/guides/source/images/habtm.png +0 -0
  161. data/doc/guides/source/images/has_many.png +0 -0
  162. data/doc/guides/source/images/has_many_through.png +0 -0
  163. data/doc/guides/source/images/has_one.png +0 -0
  164. data/doc/guides/source/images/has_one_through.png +0 -0
  165. data/doc/guides/source/images/header_backdrop.png +0 -0
  166. data/doc/guides/source/images/icons/README +0 -5
  167. data/doc/guides/source/images/icons/callouts/1.png +0 -0
  168. data/doc/guides/source/images/icons/callouts/10.png +0 -0
  169. data/doc/guides/source/images/icons/callouts/11.png +0 -0
  170. data/doc/guides/source/images/icons/callouts/12.png +0 -0
  171. data/doc/guides/source/images/icons/callouts/13.png +0 -0
  172. data/doc/guides/source/images/icons/callouts/14.png +0 -0
  173. data/doc/guides/source/images/icons/callouts/15.png +0 -0
  174. data/doc/guides/source/images/icons/callouts/2.png +0 -0
  175. data/doc/guides/source/images/icons/callouts/3.png +0 -0
  176. data/doc/guides/source/images/icons/callouts/4.png +0 -0
  177. data/doc/guides/source/images/icons/callouts/5.png +0 -0
  178. data/doc/guides/source/images/icons/callouts/6.png +0 -0
  179. data/doc/guides/source/images/icons/callouts/7.png +0 -0
  180. data/doc/guides/source/images/icons/callouts/8.png +0 -0
  181. data/doc/guides/source/images/icons/callouts/9.png +0 -0
  182. data/doc/guides/source/images/icons/caution.png +0 -0
  183. data/doc/guides/source/images/icons/example.png +0 -0
  184. data/doc/guides/source/images/icons/home.png +0 -0
  185. data/doc/guides/source/images/icons/important.png +0 -0
  186. data/doc/guides/source/images/icons/next.png +0 -0
  187. data/doc/guides/source/images/icons/note.png +0 -0
  188. data/doc/guides/source/images/icons/prev.png +0 -0
  189. data/doc/guides/source/images/icons/tip.png +0 -0
  190. data/doc/guides/source/images/icons/up.png +0 -0
  191. data/doc/guides/source/images/icons/warning.png +0 -0
  192. data/doc/guides/source/images/polymorphic.png +0 -0
  193. data/doc/guides/source/images/rails_logo_remix.gif +0 -0
  194. data/doc/guides/source/images/ruby_on_rails_by_mike_rundle2.gif +0 -0
  195. data/doc/guides/source/images/session_fixation.png +0 -0
  196. data/doc/guides/source/index.txt +0 -118
  197. data/doc/guides/source/layouts_and_rendering.txt +0 -982
  198. data/doc/guides/source/migrations/anatomy_of_a_migration.txt +0 -85
  199. data/doc/guides/source/migrations/changelog.txt +0 -5
  200. data/doc/guides/source/migrations/creating_a_migration.txt +0 -109
  201. data/doc/guides/source/migrations/foreign_keys.txt +0 -8
  202. data/doc/guides/source/migrations/index.txt +0 -22
  203. data/doc/guides/source/migrations/rakeing_around.txt +0 -111
  204. data/doc/guides/source/migrations/scheming.txt +0 -47
  205. data/doc/guides/source/migrations/using_models_in_migrations.txt +0 -46
  206. data/doc/guides/source/migrations/writing_a_migration.txt +0 -159
  207. data/doc/guides/source/routing_outside_in.txt +0 -986
  208. data/doc/guides/source/security.txt +0 -984
  209. data/doc/guides/source/stylesheets/base.css +0 -358
  210. data/doc/guides/source/stylesheets/forms.css +0 -35
  211. data/doc/guides/source/stylesheets/more.css +0 -82
  212. data/doc/guides/source/templates/guides.html.erb +0 -97
  213. data/doc/guides/source/templates/inline.css +0 -165
  214. data/doc/guides/source/testing_rails_applications.txt +0 -995
  215. data/helpers/application.rb +0 -15
  216. data/lib/commands/performance/request.rb +0 -6
  217. data/lib/commands/process/inspector.rb +0 -68
  218. data/lib/commands/process/reaper.rb +0 -149
  219. data/lib/commands/process/spawner.rb +0 -219
  220. data/lib/commands/process/spinner.rb +0 -57
  221. data/lib/commands/servers/base.rb +0 -31
  222. data/lib/commands/servers/lighttpd.rb +0 -94
  223. data/lib/commands/servers/mongrel.rb +0 -69
  224. data/lib/commands/servers/new_mongrel.rb +0 -16
  225. data/lib/commands/servers/thin.rb +0 -25
  226. data/lib/commands/servers/webrick.rb +0 -66
  227. data/lib/rails/mongrel_server/commands.rb +0 -342
  228. data/lib/rails/mongrel_server/handler.rb +0 -55
  229. data/lib/rails/rack/logger.rb +0 -28
@@ -1,97 +0,0 @@
1
- <%-
2
- manuals_index_url = ENV['MANUALSONRAILS_INDEX_URL'] || "index.html"
3
- show_toc = ENV['MANUALSONRAILS_TOC'] != 'no'
4
- -%>
5
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
6
- <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
7
- <head>
8
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
9
- <title><%- if multi_page? && !is_preamble? -%><%=h current_chapter.plain_title %> :: <% end %><%=h title %></title>
10
- <!--[if lt IE 8]>
11
- <script src="http://ie7-js.googlecode.com/svn/version/2.0(beta3)/IE8.js" type="text/javascript"></script>
12
- <![endif]-->
13
- <link href="stylesheets/base.css" media="screen" rel="Stylesheet" type="text/css" />
14
- <link href="stylesheets/forms.css" media="screen" rel="Stylesheet" type="text/css" />
15
- <link href="stylesheets/more.css" media="screen" rel="Stylesheet" type="text/css" />
16
- <style type="text/css">
17
- <%= include_file('inline.css') %>
18
- </style>
19
- </head>
20
- <body>
21
- <div id="header" <% if !show_toc %> class="notoc"<% end %>>
22
- <div id="logo">
23
- <a href="index.html" title="Ruby on Rails"><img src="images/rails_logo_remix.gif" alt="Rails" height="140" width="110" /></a>
24
- </div>
25
-
26
- <h1 id="site_title"><span>Ruby on Rails</span></h1>
27
- <h2 id="site_title_tagline">Sustainable productivity for web-application development</h2>
28
-
29
- <ul id="navMain">
30
- <li class="first-child"><a href="http://www.rubyonrails.org/" title="Ruby on Rails" class="ruby_on_rails">Ruby on Rails</a></li>
31
- <li><a class="manuals" href="index.html" title="Manuals Index">Guides Index</a></li>
32
- </ul>
33
- </div>
34
-
35
- <div id="container"<% if !show_toc %> class="notoc"<% end %>>
36
- <% if show_toc %>
37
- <div id="sidebar">
38
- <h2>Chapters</h2>
39
- <%- if multi_page? -%>
40
- <a href="<%=h chapters.first.basename %>">Preamble</a>
41
- <%- end -%>
42
- <ol>
43
- <%- if multi_page? -%>
44
- <%- for heading in table_of_contents -%>
45
- <li>
46
- <a href="<%=h heading.basename %>"><%= heading.title_without_numbers %></a>
47
- <%- if !heading.children.empty? -%>
48
- <ul>
49
- <% for h in heading.children %>
50
- <li><a href="<%=h h.basename %><%=h h.anchor %>"><%= h.title_without_numbers %></a></li>
51
- <% end %>
52
- </ul>
53
- <%- end -%>
54
- </li>
55
- <%- end -%>
56
- <%- else -%>
57
- <%- for heading in table_of_contents -%>
58
- <li>
59
- <a href="<%=h heading.anchor %>"><%= heading.title_without_numbers %></a>
60
- <%- if !heading.children.empty? -%>
61
- <ul>
62
- <% for h in heading.children %>
63
- <li><a href="<%=h h.anchor %>"><%= h.title_without_numbers %></a></li>
64
- <% end %>
65
- </ul>
66
- <%- end -%>
67
- </li>
68
- <%- end -%>
69
- <%- end -%>
70
- </ol>
71
- </div>
72
- <% end %>
73
- <div id="content">
74
- <%- if multi_page? && !is_preamble? -%>
75
- <h2 id="<%=h current_chapter.anchor_id %>"><%= current_chapter.title %></h2>
76
- <%- else -%>
77
- <h1><%=h title %></h1>
78
- <%- end -%>
79
- <%= contents %>
80
- <%- if multi_page? -%>
81
- <div id="chapter_navigation">
82
- <%- if prev_chapter -%>
83
- <div class="left-floaty">
84
- <a href="<%=h prev_chapter.basename %>">&laquo; <%= prev_chapter.title %></a>
85
- </div>
86
- <%- end -%>
87
- <%- if next_chapter -%>
88
- <div class="right-floaty">
89
- <a href="<%=h next_chapter.basename %>"><%= next_chapter.title %> &raquo;</a>
90
- </div>
91
- <%- end -%>
92
- </div>
93
- <%- end -%>
94
- </div>
95
- </div>
96
- </body>
97
- </html>
@@ -1,165 +0,0 @@
1
- div#container {
2
- max-width: 900px;
3
- padding-bottom: 3em;
4
- }
5
-
6
- div#content {
7
- margin-left: 200px;
8
- }
9
-
10
- div#container.notoc {
11
- max-width: 600px;
12
- }
13
-
14
- .notoc div#content {
15
- margin-left: 0;
16
- }
17
-
18
- pre {
19
- line-height: 1.4em;
20
- }
21
-
22
- #content p tt {
23
- background: #eeeeee;
24
- border: solid 1px #cccccc;
25
- padding: 3px;
26
- }
27
-
28
- dt {
29
- font-weight: bold;
30
- }
31
-
32
- #content dt tt {
33
- font-size: 10pt;
34
- }
35
-
36
- dd {
37
- margin-left: 3em;
38
- }
39
-
40
- #content dt tt, #content pre tt {
41
- background: none;
42
- padding: 0;
43
- border: 0;
44
- }
45
-
46
- #content .olist ol {
47
- margin-left: 2em;
48
- }
49
-
50
- #header {
51
- position: relative;
52
- max-width: 840px;
53
- margin-left: auto;
54
- margin-right: auto;
55
- }
56
-
57
- #header.notoc {
58
- max-width: 580px;
59
- }
60
-
61
- #logo {
62
- position: absolute;
63
- left: 10px;
64
- top: 10px;
65
- width: 110px;
66
- height: 140px;
67
- }
68
-
69
- div#header h1#site_title {
70
- background: url('images/ruby_on_rails_by_mike_rundle2.gif') top left no-repeat;
71
- position: absolute;
72
- width: 392px;
73
- height: 55px;
74
- left: 145px;
75
- top: 20px;
76
- margin: 0;
77
- padding: 0;
78
- }
79
-
80
- #site_title span {
81
- display: none;
82
- }
83
-
84
- #site_title_tagline {
85
- display: none;
86
- }
87
-
88
- ul#navMain {
89
- position: absolute;
90
- margin: 0;
91
- padding: 0;
92
- top: 97px;
93
- left: 145px;
94
- }
95
-
96
- .left-floaty, .right-floaty {
97
- padding: 15px;
98
- }
99
-
100
- .admonitionblock,
101
- .tableblock {
102
- margin-left: 1em;
103
- margin-right: 1em;
104
- margin-top: 0.25em;
105
- margin-bottom: 1em;
106
- }
107
-
108
- .admonitionblock .icon {
109
- padding-right: 8px;
110
- }
111
-
112
- .admonitionblock .content {
113
- border: solid 1px #ffda78;
114
- background: #fffebd;
115
- padding: 10px;
116
- padding-top: 8px;
117
- padding-bottom: 8px;
118
- }
119
-
120
- .admonitionblock .title {
121
- font-size: 140%;
122
- margin-bottom: 0.5em;
123
- }
124
-
125
- .tableblock table {
126
- border: solid 1px #aaaaff;
127
- background: #f0f0ff;
128
- }
129
-
130
- .tableblock th {
131
- background: #e0e0e0;
132
- }
133
-
134
- .tableblock th,
135
- .tableblock td {
136
- padding: 3px;
137
- padding-left: 5px;
138
- padding-right: 5px;
139
- }
140
-
141
- .sidebarblock {
142
- margin-top: 0.25em;
143
- margin: 1em;
144
- border: solid 1px #ccccbb;
145
- padding: 8px;
146
- background: #ffffe0;
147
- }
148
-
149
- .sidebarblock .sidebar-title {
150
- font-size: 140%;
151
- font-weight: 600;
152
- margin-bottom: 0.3em;
153
- }
154
-
155
- .sidebarblock .sidebar-content > .para:last-child > p {
156
- margin-bottom: 0;
157
- }
158
-
159
- .sidebarblock .sidebar-title a {
160
- text-decoration: none;
161
- }
162
-
163
- .sidebarblock .sidebar-title a:hover {
164
- text-decoration: underline;
165
- }
@@ -1,995 +0,0 @@
1
- A Guide to Testing Rails Applications
2
- =====================================
3
-
4
- This guide covers built-in mechanisms offered by Rails to test your application. By referring to this guide, you will be able to:
5
-
6
- * Understand Rails testing terminology
7
- * Write unit, functional and integration tests for your application
8
- * Identify other popular testing approaches and plugins
9
-
10
- This guide won't teach you to write a Rails application; it assumes basic familiarity with the Rails way of doing things.
11
-
12
- == Why Write Tests for your Rails Applications? ==
13
-
14
- * Rails makes it super easy to write your tests. It starts by producing skeleton test code in background while you are creating your models and controllers.
15
- * By simply running your Rails tests you can ensure your code adheres to the desired functionality even after some major code refactoring.
16
- * Rails tests can also simulate browser requests and thus you can test your application's response without having to test it through your browser.
17
-
18
- == Introduction to Testing ==
19
-
20
- 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.
21
-
22
- === The 3 Environments ===
23
-
24
- Every Rails application you build has 3 sides: a side for production, a side for development, and a side for testing.
25
-
26
- One place you'll find this distinction is in the +config/database.yml+ file. This YAML configuration file has 3 different sections defining 3 unique database setups:
27
-
28
- * production
29
- * development
30
- * test
31
-
32
- This allows you to set up and interact with test data without any danger of your tests altering data from your production environment.
33
-
34
- For example, suppose you need to test your new +delete_this_user_and_every_everything_associated_with_it+ function. Wouldn't you want to run this in an environment where it makes no difference if you destroy data or not?
35
-
36
- When you do end up destroying your testing database (and it will happen, trust me), you can rebuild it from scratch according to the specs defined in the development database. You can do this by running +rake db:test:prepare+.
37
-
38
- === Rails Sets up for Testing from the Word Go ===
39
-
40
- Rails creates a +test+ folder for you as soon as you create a Rails project using +rails _application_name_+. If you list the contents of this folder then you shall see:
41
-
42
- [source,shell]
43
- ------------------------------------------------------
44
- $ ls -F test/
45
-
46
- fixtures/ functional/ integration/ test_helper.rb unit/
47
- ------------------------------------------------------
48
-
49
- The +unit+ folder is meant to hold tests for your models, the +functional+ folder is meant to hold tests for your controllers, and the +integration+ folder is meant to hold tests that involve any number of controllers interacting. Fixtures are a way of organizing test data; they reside in the +fixtures+ folder. The +test_helper.rb+ file holds the default configuration for your tests.
50
-
51
- === 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 and assume one of two formats: *YAML* or *CSV*. In this guide we will use *YAML* which is the preferred format.
58
-
59
- You'll find fixtures under your +test/fixtures+ directory. When you run +script/generate model+ to create a new model, fixture stubs will be automatically created and placed in this directory.
60
-
61
- ==== 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
- [source,ruby]
68
- ---------------------------------------------
69
- # low & behold! I am a YAML comment!
70
- david:
71
- name: David Heinemeier Hansson
72
- birthday: 1979-10-15
73
- profession: Systems development
74
-
75
- steve:
76
- name: Steve Ross Kellock
77
- birthday: 1974-09-27
78
- profession: guy with keyboard
79
- ---------------------------------------------
80
-
81
- Each fixture is given a name followed by an indented list of colon-separated key/value pairs. Records are separated by a blank space. You can place comments in a fixture file by using the # character in the first column.
82
-
83
- ==== ERb'in It Up ====
84
-
85
- ERb allows you embed ruby code within templates. Both the YAML and CSV fixture formats are pre-processed with ERb when you load fixtures. This allows you to use Ruby to help you generate some sample data.
86
-
87
- [source, ruby]
88
- --------------------------------------------------------------
89
- <% earth_size = 20 -%>
90
- mercury:
91
- size: <%= earth_size / 50 %>
92
- brightest_on: <%= 113.days.ago.to_s(:db) %>
93
-
94
- venus:
95
- size: <%= earth_size / 2 %>
96
- brightest_on: <%= 67.days.ago.to_s(:db) %>
97
-
98
- mars:
99
- size: <%= earth_size - 69 %>
100
- brightest_on: <%= 13.days.from_now.to_s(:db) %>
101
- --------------------------------------------------------------
102
-
103
- Anything encased within the
104
-
105
- [source, ruby]
106
- ------------------------
107
- <% %>
108
- ------------------------
109
-
110
- tag is considered Ruby code. When this fixture is loaded, the +size+ attribute of the three records will be set to 20/50, 20/2, and 20-69 respectively. The +brightest_on+ attribute will also be evaluated and formatted by Rails to be compatible with the database.
111
-
112
- ==== Fixtures in Action ====
113
-
114
- Rails by default automatically loads all fixtures from the 'test/fixtures' folder for your unit and functional test. Loading involves three steps:
115
-
116
- * Remove any existing data from the table corresponding to the fixture
117
- * Load the fixture data into the table
118
- * Dump the fixture data into a variable in case you want to access it directly
119
-
120
- ==== Hashes with Special Powers ====
121
-
122
- Fixtures are basically Hash objects. As mentioned in point #3 above, you can access the hash object directly because it is automatically setup as a local variable of the test case. For example:
123
-
124
- [source, ruby]
125
- --------------------------------------------------------------
126
- # this will return the Hash for the fixture named david
127
- users(:david)
128
-
129
- # this will return the property for david called id
130
- users(:david).id
131
- --------------------------------------------------------------
132
-
133
- Fixtures can also transform themselves into the form of the original class. Thus, you can get at the methods only available to that class.
134
-
135
- [source, ruby]
136
- --------------------------------------------------------------
137
- # using the find method, we grab the "real" david as a User
138
- david = users(:david).find
139
-
140
- # and now we have access to methods only available to a User class
141
- email(david.girlfriend.email, david.location_tonight)
142
- --------------------------------------------------------------
143
-
144
- == Unit Testing your Models ==
145
-
146
- In Rails, unit tests are what you write to test your models.
147
-
148
- 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 practises. I will be using examples from this generated code and would be supplementing it with additional examples where necessary.
149
-
150
- NOTE: For more information on Rails _scaffolding_, refer to link:../getting_started_with_rails.html[Getting Started with Rails]
151
-
152
- When you use +script/generate scaffold+, for a resource among other things it creates a test stub in the +test/unit+ folder:
153
-
154
- -------------------------------------------------------
155
- $ script/generate scaffold post title:string body:text
156
- ...
157
- create app/models/post.rb
158
- create test/unit/post_test.rb
159
- create test/fixtures/posts.yml
160
- ...
161
- -------------------------------------------------------
162
-
163
- The default test stub in +test/unit/post_test.rb+ looks like this:
164
-
165
- [source,ruby]
166
- --------------------------------------------------
167
- require 'test_helper'
168
-
169
- class PostTest < ActiveSupport::TestCase
170
- # Replace this with your real tests.
171
- def test_truth
172
- assert true
173
- end
174
- end
175
- --------------------------------------------------
176
-
177
- A line by line examination of this file will help get you oriented to Rails testing code and terminology.
178
-
179
- [source,ruby]
180
- --------------------------------------------------
181
- require 'test_helper'
182
- --------------------------------------------------
183
-
184
- As you know by now that `test_helper.rb` specifies the default configuration to run our tests. This is included with all the tests, so any methods added to this file are available to all your tests.
185
-
186
- [source,ruby]
187
- --------------------------------------------------
188
- class PostTest < ActiveSupport::TestCase
189
- --------------------------------------------------
190
-
191
- 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.
192
-
193
- [source,ruby]
194
- --------------------------------------------------
195
- def test_truth
196
- --------------------------------------------------
197
-
198
- Any method defined within a test case that begins with +test+ (case sensitive) is simply called a test. So, +test_password+, +test_valid_password+ and +testValidPassword+ all are legal test names and are run automatically when the test case is run.
199
-
200
- [source,ruby]
201
- --------------------------------------------------
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
- * is 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 the test passes.
213
-
214
- === Preparing you Application for Testing ===
215
-
216
- 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:
217
-
218
- [source, shell]
219
- -------------------------------------------------------
220
- $ rake db:migrate
221
- ...
222
- $ rake db:test:load
223
- -------------------------------------------------------
224
-
225
- Above +rake db:migrate+ runs any pending migrations on the _developemnt_ environment and updates +db/schema.rb+. +rake db:test:load+ recreates the test database from the current db/schema.rb. On subsequent attempts it is a good to first run +db:test:prepare+ as it first checks for pending migrations and warns you appropriately.
226
-
227
- NOTE: +db:test:prepare+ will fail with an error if db/schema.rb doesn't exists.
228
-
229
- ==== Rake Tasks for Preparing you Application for Testing ==
230
-
231
- [grid="all"]
232
- --------------------------------`----------------------------------------------------
233
- Tasks Description
234
- ------------------------------------------------------------------------------------
235
- +rake db:test:clone+ Recreate the test database from the current environment's database schema
236
- +rake db:test:clone_structure+ Recreate the test databases from the development structure
237
- +rake db:test:load+ Recreate the test database from the current +schema.rb+
238
- +rake db:test:prepare+ Check for pending migrations and load the test schema
239
- +rake db:test:purge+ Empty the test database.
240
- ------------------------------------------------------------------------------------
241
-
242
- TIP: You can see all these rake tasks and their descriptions by running +rake --tasks --describe+
243
-
244
- === Running Tests ===
245
-
246
- Running a test is as simple as invoking the file containing the test cases through Ruby:
247
-
248
- [source, shell]
249
- -------------------------------------------------------
250
- $ cd test
251
- $ ruby unit/post_test.rb
252
-
253
- Loaded suite unit/post_test
254
- Started
255
- .
256
- Finished in 0.023513 seconds.
257
-
258
- 1 tests, 1 assertions, 0 failures, 0 errors
259
- -------------------------------------------------------
260
-
261
- This will run all the test methods from the test case.
262
-
263
- You can also run a particular test method from the test case by using the +-n+ switch with the +test method name+.
264
-
265
- -------------------------------------------------------
266
- $ ruby unit/post_test.rb -n test_truth
267
-
268
- Loaded suite unit/post_test
269
- Started
270
- .
271
- Finished in 0.023513 seconds.
272
-
273
- 1 tests, 1 assertions, 0 failures, 0 errors
274
- -------------------------------------------------------
275
-
276
- 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.
277
-
278
- To see how a test failure is reported, you can add a failing test to the +post_test.rb+ test case.
279
-
280
- [source,ruby]
281
- --------------------------------------------------
282
- def test_should_not_save_post_without_title
283
- post = Post.new
284
- assert !post.save
285
- end
286
- --------------------------------------------------
287
-
288
- Let us run this newly added test.
289
-
290
- -------------------------------------------------------
291
- $ ruby unit/post_test.rb -n test_should_not_save_post_without_title
292
- Loaded suite unit/post_test
293
- Started
294
- F
295
- Finished in 0.197094 seconds.
296
-
297
- 1) Failure:
298
- test_should_not_save_post_without_title(PostTest)
299
- [unit/post_test.rb:11:in `test_should_not_save_post_without_title'
300
- /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `__send__'
301
- /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `run']:
302
- <false> is not true.
303
-
304
- 1 tests, 1 assertions, 1 failures, 0 errors
305
- -------------------------------------------------------
306
-
307
- 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:
308
-
309
- [source,ruby]
310
- --------------------------------------------------
311
- def test_should_not_save_post_without_title
312
- post = Post.new
313
- assert !post.save, "Saved the post without a title"
314
- end
315
- --------------------------------------------------
316
-
317
- Running this test shows the friendlier assertion message:
318
-
319
- -------------------------------------------------------
320
- $ ruby unit/post_test.rb -n test_should_not_save_post_without_title
321
- Loaded suite unit/post_test
322
- Started
323
- F
324
- Finished in 0.198093 seconds.
325
-
326
- 1) Failure:
327
- test_should_not_save_post_without_title(PostTest)
328
- [unit/post_test.rb:11:in `test_should_not_save_post_without_title'
329
- /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `__send__'
330
- /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `run']:
331
- Saved the post without a title.
332
- <false> is not true.
333
-
334
- 1 tests, 1 assertions, 1 failures, 0 errors
335
- -------------------------------------------------------
336
-
337
- Now to get this test to pass we can add a model level validation for the _title_ field.
338
-
339
- [source,ruby]
340
- --------------------------------------------------
341
- class Post < ActiveRecord::Base
342
- validates_presence_of :title
343
- end
344
- --------------------------------------------------
345
-
346
- Now the test should pass. Let us verify by running the test again:
347
-
348
- -------------------------------------------------------
349
- $ ruby unit/post_test.rb -n test_should_not_save_post_without_title
350
- Loaded suite unit/post_test
351
- Started
352
- .
353
- Finished in 0.193608 seconds.
354
-
355
- 1 tests, 1 assertions, 0 failures, 0 errors
356
- -------------------------------------------------------
357
-
358
- 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).
359
-
360
- 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 link:http://andrzejonsoftware.blogspot.com/2007/05/15-tdd-steps-to-create-rails.html[15 TDD steps to create a Rails application].
361
-
362
- To see how an error gets reported, here's a test containing an error:
363
-
364
- [source,ruby]
365
- --------------------------------------------------
366
- def test_should_report_error
367
- # some_undefined_variable is not defined elsewhere in the test case
368
- some_undefined_variable
369
- assert true
370
- end
371
- --------------------------------------------------
372
-
373
- Now you can see even more output in the console from running the tests:
374
-
375
- -------------------------------------------------------
376
- $ ruby unit/post_test.rb -n test_should_report_error
377
- Loaded suite unit/post_test
378
- Started
379
- E
380
- Finished in 0.195757 seconds.
381
-
382
- 1) Error:
383
- test_should_report_error(PostTest):
384
- NameError: undefined local variable or method `some_undefined_variable' for #<PostTest:0x2cc9de8>
385
- /opt/local/lib/ruby/gems/1.8/gems/actionpack-2.1.1/lib/action_controller/test_process.rb:467:in `method_missing'
386
- unit/post_test.rb:16:in `test_should_report_error'
387
- /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `__send__'
388
- /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `run'
389
-
390
- 1 tests, 0 assertions, 0 failures, 1 errors
391
- -------------------------------------------------------
392
-
393
- Notice the 'E' in the output. It denotes a test with error.
394
-
395
- NOTE: The execution of each test method stops as soon as any error or a assertion failure is encountered, and the test suite continues with the next method. All test methods are executed in alphabetical order.
396
-
397
- === What to Include in Your Unit Tests ===
398
-
399
- 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.
400
-
401
- === Assertions Available ===
402
-
403
- 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.
404
-
405
- There are a bunch of different types of assertions you can use. Here's the complete list of assertions that ship with +test/unit+, the testing library used by Rails. The +[msg]+ parameter is an optional string message you can specify to make your test failure messages clearer. It's not required.
406
-
407
- [grid="all"]
408
- `-----------------------------------------------------------------`------------------------------------------------------------------------
409
- Assertion Purpose
410
- ------------------------------------------------------------------------------------------------------------------------------------------
411
- +assert( boolean, [msg] )+ Ensures that the object/expression is true.
412
- +assert_equal( obj1, obj2, [msg] )+ Ensures that +obj1 == obj2+ is true.
413
- +assert_not_equal( obj1, obj2, [msg] )+ Ensures that +obj1 == obj2+ is false.
414
- +assert_same( obj1, obj2, [msg] )+ Ensures that +obj1.equal?(obj2)+ is true.
415
- +assert_not_same( obj1, obj2, [msg] )+ Ensures that +obj1.equal?(obj2)+ is false.
416
- +assert_nil( obj, [msg] )+ Ensures that +obj.nil?+ is true.
417
- +assert_not_nil( obj, [msg] )+ Ensures that +obj.nil?+ is false.
418
- +assert_match( regexp, string, [msg] )+ Ensures that a string matches the regular expression.
419
- +assert_no_match( regexp, string, [msg] )+ Ensures that a string doesn't matches the regular expression.
420
- +assert_in_delta( expecting, actual, delta, [msg] )+ Ensures that the numbers `expecting` and `actual` are within `delta` of each other.
421
- +assert_throws( symbol, [msg] ) { block }+ Ensures that the given block throws the symbol.
422
- +assert_raises( exception1, exception2, ... ) { block }+ Ensures that the given block raises one of the given exceptions.
423
- +assert_nothing_raised( exception1, exception2, ... ) { block }+ Ensures that the given block doesn't raise one of the given exceptions.
424
- +assert_instance_of( class, obj, [msg] )+ Ensures that +obj+ is of the +class+ type.
425
- +assert_kind_of( class, obj, [msg] )+ Ensures that +obj+ is or descends from +class+.
426
- +assert_respond_to( obj, symbol, [msg] )+ Ensures that +obj+ has a method called +symbol+.
427
- +assert_operator( obj1, operator, obj2, [msg] )+ Ensures that +obj1.operator(obj2)+ is true.
428
- +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?
429
- +flunk( [msg] )+ Ensures failure. This is useful to explicitly mark a test that isn't finished yet.
430
- ------------------------------------------------------------------------------------------------------------------------------------------
431
-
432
- 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.
433
-
434
- NOTE: Creating your own assertions is an advanced topic that we won't cover in this tutorial.
435
-
436
- === Rails Specific Assertions ===
437
-
438
- Rails adds some custom assertions of its own to the +test/unit+ framework:
439
-
440
- [grid="all"]
441
- `----------------------------------------------------------------------------------`-------------------------------------------------------
442
- Assertion Purpose
443
- ------------------------------------------------------------------------------------------------------------------------------------------
444
- +assert_valid(record)+ Ensures that the passed record is valid by Active Record standards and returns any error messages if it is not.
445
- +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.
446
- +assert_no_difference(expressions, message = nil, &block)+ Asserts that the numeric result of evaluating an expression is not changed before and after invoking the passed in block.
447
- +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.
448
- +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.
449
- +assert_response(type, message = nil)+ Asserts that the response comes with a specific status code. You can specify +:success+ to indicate 200, +:redirect+ to indicate 300-399, +:missing+ to indicate 404, or +:error+ to match the 500-599 range
450
- +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.
451
- +assert_template(expected = nil, message=nil)+ Asserts that the request was rendered with the appropriate template file.
452
- ------------------------------------------------------------------------------------------------------------------------------------------
453
-
454
- You'll see the usage of some of these assertions in the next chapter.
455
-
456
- == Functional Tests for Your Controllers ==
457
-
458
- 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.
459
-
460
- === What to include in your Functional Tests ===
461
-
462
- You should test for things such as:
463
-
464
- * was the web request successful?
465
- * was the user redirected to the right page?
466
- * was the user successfully authenticated?
467
- * was the correct object stored in the response template?
468
- * was the appropriate message displayed to the user in the view
469
-
470
- Now that we have used Rails scaffold generator for our +Post+ resource, it has already created the controller code and functional tests. You can take look at the file +posts_controller_test.rb+ in the +test/functional+ directory.
471
-
472
- Let me take you through one such test, +test_should_get_index+ from the file +posts_controller_test.rb+.
473
-
474
- [source,ruby]
475
- --------------------------------------------------
476
- def test_should_get_index
477
- get :index
478
- assert_response :success
479
- assert_not_nil assigns(:posts)
480
- end
481
- --------------------------------------------------
482
-
483
- 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.
484
-
485
- The +get+ method kicks off the web request and populates the results into the response. It accepts 4 arguments:
486
-
487
- * The action of the controller you are requesting. This can be in the form of a string or a symbol.
488
- * An optional hash of request parameters to pass into the action (eg. query string parameters or post variables).
489
- * An optional hash of session variables to pass along with the request.
490
- * An optional hash of flash values.
491
-
492
- Example: Calling the +:show+ action, passing an +id+ of 12 as the +params+ and setting a +user_id+ of 5 in the session:
493
-
494
- [source,ruby]
495
- --------------------------------------------------
496
- get(:show, {'id' => "12"}, {'user_id' => 5})
497
- --------------------------------------------------
498
-
499
- Another example: Calling the +:view+ action, passing an +id+ of 12 as the +params+, this time with no session, but with a flash message.
500
-
501
- [source,ruby]
502
- --------------------------------------------------
503
- get(:view, {'id' => '12'}, nil, {'message' => 'booya!'})
504
- --------------------------------------------------
505
-
506
- 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.
507
-
508
- Let us modify +test_should_create_post+ test in +posts_controller_test.rb+ so that all our test pass:
509
-
510
- [source,ruby]
511
- --------------------------------------------------
512
- def test_should_create_post
513
- assert_difference('Post.count') do
514
- post :create, :post => { :title => 'Some title'}
515
- end
516
-
517
- assert_redirected_to post_path(assigns(:post))
518
- end
519
- --------------------------------------------------
520
-
521
- Now you can try running all the tests and they should pass.
522
-
523
- === Available Request Types for Functional Tests ===
524
-
525
- If you're familiar with the HTTP protocol, you'll know that +get+ is a type of request. There are 5 request types supported in Rails functional tests:
526
-
527
- * +get+
528
- * +post+
529
- * +put+
530
- * +head+
531
- * +delete+
532
-
533
- 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.
534
-
535
- === The 4 Hashes of the Apocalypse ===
536
-
537
- 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:
538
-
539
- * +assigns+ - Any objects that are stored as instance variables in actions for use in views.
540
- * +cookies+ - Any cookies that are set.
541
- * +flash+ - Any objects living in the flash.
542
- * +session+ - Any object living in session variables.
543
-
544
- 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:
545
-
546
- [source,ruby]
547
- --------------------------------------------------
548
- flash["gordon"] flash[:gordon]
549
- session["shmession"] session[:shmession]
550
- cookies["are_good_for_u"] cookies[:are_good_for_u]
551
-
552
- # Because you can't use assigns[:something] for historical reasons:
553
- assigns["something"] assigns(:something)
554
- --------------------------------------------------
555
-
556
- === Instance Variables Available ===
557
-
558
- You also have access to three instance variables in your functional tests:
559
-
560
- * +@controller+ - The controller processing the request
561
- * +@request+ - The request
562
- * +@response+ - The response
563
-
564
- === A Fuller Functional Test Example
565
-
566
- Here's another example that uses +flash+, +assert_redirected_to+, and +assert_difference+:
567
-
568
- [source,ruby]
569
- --------------------------------------------------
570
- def test_should_create_post
571
- assert_difference('Post.count') do
572
- post :create, :post => { :title => 'Hi', :body => 'This is my first post.'}
573
- end
574
- assert_redirected_to post_path(assigns(:post))
575
- assert_equal 'Post was successfully created.', flash[:notice]
576
- end
577
- --------------------------------------------------
578
-
579
- === Testing Views ===
580
-
581
- 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.
582
-
583
- NOTE: You may find references to +assert_tag+ in other documentation, but this is now deprecated in favor of +assert_select+.
584
-
585
- There are two forms of +assert_select+:
586
-
587
- +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.
588
-
589
- +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.
590
-
591
- For example, you could verify the contents on the title element in your response with:
592
-
593
- [source,ruby]
594
- --------------------------------------------------
595
- assert_select 'title', "Welcome to Rails Testing Guide"
596
- --------------------------------------------------
597
-
598
- You can also use nested +assert_select+ blocks. In this case the inner +assert_select+ will run the assertion on each element selected by the outer `assert_select` block:
599
-
600
- [source,ruby]
601
- --------------------------------------------------
602
- assert_select 'ul.navigation' do
603
- assert_select 'li.menu_item'
604
- end
605
- --------------------------------------------------
606
-
607
- The +assert_select+ assertion is quite powerful. For more advanced usage, refer to its link:http://api.rubyonrails.com/classes/ActionController/Assertions/SelectorAssertions.html#M000749[documentation].
608
-
609
- ==== Additional View-based Assertions ====
610
-
611
- There are more assertions that are primarily used in testing views:
612
-
613
- [grid="all"]
614
- `----------------------------------------------------------------------------------`-------------------------------------------------------
615
- Assertion Purpose
616
- ------------------------------------------------------------------------------------------------------------------------------------------
617
- +assert_select_email+ Allows you to make assertions on the body of an e-mail.
618
- +assert_select_rjs+ Allows you to make assertions on RJS response. +assert_select_rjs+ has variants which allow you to narrow down on the updated element or even a particular operation on an element.
619
- +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.
620
- +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.
621
- ------------------------------------------------------------------------------------------------------------------------------------------
622
-
623
- Here's an example of using +assert_select_email+:
624
-
625
- [source,ruby]
626
- --------------------------------------------------
627
- assert_select_email do
628
- assert_select 'small', 'Please click the "Unsubscribe" link if you want to opt-out.'
629
- end
630
- --------------------------------------------------
631
-
632
- == Integration Testing ==
633
-
634
- 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.
635
-
636
- 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.
637
-
638
- [source, shell]
639
- --------------------------------------------------
640
- $ script/generate integration_test user_flows
641
- exists test/integration/
642
- create test/integration/user_flows_test.rb
643
- --------------------------------------------------
644
-
645
- Here's what a freshly-generated integration test looks like:
646
-
647
- [source,ruby]
648
- --------------------------------------------------
649
- require 'test_helper'
650
-
651
- class UserFlowsTest < ActionController::IntegrationTest
652
- # fixtures :your, :models
653
-
654
- # Replace this with your real tests.
655
- def test_truth
656
- assert true
657
- end
658
- end
659
- --------------------------------------------------
660
-
661
- Integration tests inherit from +ActionController::IntegrationTest+. This makes available some additional helpers to use in your integration tests. Also you need to explicitly include the fixtures to be made available to the test.
662
-
663
- === Helpers Available for Integration tests ===
664
-
665
- In addition to the standard testing helpers, there are some additional helpers available to integration tests:
666
-
667
- [grid="all"]
668
- `----------------------------------------------------------------------------------`-------------------------------------------------------
669
- Helper Purpose
670
- ------------------------------------------------------------------------------------------------------------------------------------------
671
- +https?+ Returns +true+ if the session is mimicking a secure HTTPS request.
672
- +https!+ Allows you to mimic a secure HTTPS request.
673
- +host!+ Allows you to set the host name to use in the next request.
674
- +redirect?+ Returns +true+ if the last request was a redirect.
675
- +follow_redirect!+ Follows a single redirect response.
676
- +request_via_redirect(http_method, path, [parameters], [headers])+ Allows you to make an HTTP request and follow any subsequent redirects.
677
- +post_via_redirect(path, [parameters], [headers])+ Allows you to make an HTTP POST request and follow any subsequent redirects.
678
- +get_via_redirect(path, [parameters], [headers])+ Allows you to make an HTTP GET request and follow any subsequent redirects.
679
- +put_via_redirect(path, [parameters], [headers])+ Allows you to make an HTTP PUT request and follow any subsequent redirects.
680
- +delete_via_redirect(path, [parameters], [headers])+ Allows you to make an HTTP DELETE request and follow any subsequent redirects.
681
- +open_session+ Opens a new session instance.
682
- ------------------------------------------------------------------------------------------------------------------------------------------
683
-
684
- === Integration Testing Examples ===
685
-
686
- A simple integration test that exercises multiple controllers:
687
-
688
- [source,ruby]
689
- --------------------------------------------------
690
- require 'test_helper'
691
-
692
- class UserFlowsTest < ActionController::IntegrationTest
693
- fixtures :users
694
-
695
- def test_login_and_browse_site
696
- # login via https
697
- https!
698
- get "/login"
699
- assert_response :success
700
-
701
- post_via_redirect "/login", :username => users(:avs).username, :password => users(:avs).password
702
- assert_equal '/welcome', path
703
- assert_equal 'Welcome avs!', flash[:notice]
704
-
705
- https!(false)
706
- get "/posts/all"
707
- assert_response :success
708
- assert assigns(:products)
709
- end
710
- end
711
- --------------------------------------------------
712
-
713
- 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.
714
-
715
- Here's an example of multiple sessions and custom DSL in an integration test
716
-
717
- [source,ruby]
718
- --------------------------------------------------
719
- require 'test_helper'
720
-
721
- class UserFlowsTest < ActionController::IntegrationTest
722
- fixtures :users
723
-
724
- def test_login_and_browse_site
725
-
726
- # User avs logs in
727
- avs = login(:avs)
728
- # User guest logs in
729
- guest = login(:guest)
730
-
731
- # Both are now available in different sessions
732
- assert_equal 'Welcome avs!', avs.flash[:notice]
733
- assert_equal 'Welcome guest!', guest.flash[:notice]
734
-
735
- # User avs can browse site
736
- avs.browses_site
737
- # User guest can browse site aswell
738
- guest.browses_site
739
-
740
- # Continue with other assertions
741
- end
742
-
743
- private
744
-
745
- module CustomDsl
746
- def browses_site
747
- get "/products/all"
748
- assert_response :success
749
- assert assigns(:products)
750
- end
751
- end
752
-
753
- def login(user)
754
- open_session do |sess|
755
- sess.extend(CustomDsl)
756
- u = users(user)
757
- sess.https!
758
- sess.post "/login", :username => u.username, :password => u.password
759
- assert_equal '/welcome', path
760
- sess.https!(false)
761
- end
762
- end
763
- end
764
- --------------------------------------------------
765
-
766
- == Rake Tasks for Running your Tests ==
767
-
768
- You don't need to set up and run your tests by hand on a test-by-test basis. Rails comes with a number of rake tasks to help in testing. The table below lists all rake tasks that come along in the default Rakefile when you initiate a Rail project.
769
-
770
- [grid="all"]
771
- --------------------------------`----------------------------------------------------
772
- Tasks Description
773
- ------------------------------------------------------------------------------------
774
- +rake test+ Runs all unit, functional and integration tests. You can also simply run +rake+ as the _test_ target is the default.
775
- +rake test:units+ Runs all the unit tests from +test/unit+
776
- +rake test:functionals+ Runs all the functional tests from +test/functional+
777
- +rake test:integration+ Runs all the integration tests from +test/integration+
778
- +rake test:recent+ Tests recent changes
779
- +rake test:uncommitted+ Runs all the tests which are uncommitted. Only supports Subversion
780
- +rake test:plugins+ Run all the plugin tests from +vendor/plugins/*/**/test+ (or specify with +PLUGIN=_name_+)
781
- ------------------------------------------------------------------------------------
782
-
783
-
784
- == Brief Note About Test::Unit ==
785
-
786
- Ruby ships with a boat load of libraries. One little gem of a library is +Test::Unit+, a framework for unit testing in Ruby. All the basic assertions discussed above are actually defined in +Test::Unit::Assertions+. The class +ActiveSupport::TestCase+ which we have been using in our unit and functional tests extends +Test::Unit::TestCase+ that it is how we can use all the basic assertions in our tests.
787
-
788
- NOTE: For more information on +Test::Unit+, refer to link:http://ruby-doc.org/stdlib/libdoc/test/unit/rdoc/[test/unit Documentation]
789
-
790
- == Setup and Teardown ==
791
-
792
- 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:
793
-
794
- [source,ruby]
795
- --------------------------------------------------
796
- require 'test_helper'
797
-
798
- class PostsControllerTest < ActionController::TestCase
799
-
800
- # called before every single test
801
- def setup
802
- @post = posts(:one)
803
- end
804
-
805
- # called after every single test
806
- def teardown
807
- # as we are re-initializing @post before every test
808
- # setting it to nil here is not essential but I hope
809
- # you understand how you can use the teardown method
810
- @post = nil
811
- end
812
-
813
- def test_should_show_post
814
- get :show, :id => @post.id
815
- assert_response :success
816
- end
817
-
818
- def test_should_destroy_post
819
- assert_difference('Post.count', -1) do
820
- delete :destroy, :id => @post.id
821
- end
822
-
823
- assert_redirected_to posts_path
824
- end
825
-
826
- end
827
- --------------------------------------------------
828
-
829
- 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:
830
-
831
- * a block
832
- * a method (like in the earlier example)
833
- * a method name as a symbol
834
- * a lambda
835
-
836
- Let's see the earlier example by specifying +setup+ callback by specifying a method name as a symbol:
837
-
838
- [source,ruby]
839
- --------------------------------------------------
840
- require '../test_helper'
841
-
842
- class PostsControllerTest < ActionController::TestCase
843
-
844
- # called before every single test
845
- setup :initialize_post
846
-
847
- # called after every single test
848
- def teardown
849
- @post = nil
850
- end
851
-
852
- def test_should_show_post
853
- get :show, :id => @post.id
854
- assert_response :success
855
- end
856
-
857
- def test_should_update_post
858
- put :update, :id => @post.id, :post => { }
859
- assert_redirected_to post_path(assigns(:post))
860
- end
861
-
862
- def test_should_destroy_post
863
- assert_difference('Post.count', -1) do
864
- delete :destroy, :id => @post.id
865
- end
866
-
867
- assert_redirected_to posts_path
868
- end
869
-
870
- private
871
-
872
- def initialize_post
873
- @post = posts(:one)
874
- end
875
-
876
- end
877
- --------------------------------------------------
878
-
879
- == Testing Routes ==
880
-
881
- Like everything else in you Rails application, it's recommended to test you routes. An example test for a route in the default +show+ action of +Posts+ controller above should look like:
882
-
883
- [source,ruby]
884
- --------------------------------------------------
885
- def test_should_route_to_post
886
- assert_routing '/posts/1', { :controller => "posts", :action => "show", :id => "1" }
887
- end
888
- --------------------------------------------------
889
-
890
- == Testing Your Mailers ==
891
-
892
- Testing mailer classes requires some specific tools to do a thorough job.
893
-
894
- === Keeping the Postman in Check ===
895
-
896
- Your +ActionMailer+ classes -- like every other part of your Rails application -- should be tested to ensure that it is working as expected.
897
-
898
- The goals of testing your +ActionMailer+ classes are to ensure that:
899
-
900
- * emails are being processed (created and sent)
901
- * the email content is correct (subject, sender, body, etc)
902
- * the right emails are being sent at the right times
903
-
904
- ==== From All Sides ====
905
-
906
- There are two aspects of testing your mailer, the unit tests and the functional tests. In the unit tests, you run the mailer in isolation with tightly controlled inputs and compare the output to a knownvalue (a fixture -- yay! more fixtures!). In the functional tests you don't so much test the minute details produced by the mailer Instead we test that our controllers and models are using the mailer in the right way. You test to prove that the right email was sent at the right time.
907
-
908
- === Unit Testing ===
909
-
910
- 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.
911
-
912
- ==== Revenge of the Fixtures ====
913
-
914
- 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.
915
-
916
- 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.
917
-
918
- ==== The Basic Test case ====
919
-
920
- 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.
921
-
922
- [source, ruby]
923
- -------------------------------------------------
924
- require 'test_helper'
925
-
926
- class UserMailerTest < ActionMailer::TestCase
927
- tests UserMailer
928
- def test_invite
929
- @expected.from = 'me@example.com'
930
- @expected.to = 'friend@example.com'
931
- @expected.subject = "You have been invited by #{@expected.from}"
932
- @expected.body = read_fixture('invite')
933
- @expected.date = Time.now
934
-
935
- assert_equal @expected.encoded, UserMailer.create_invite('me@example.com', 'friend@example.com', @expected.date).encoded
936
- end
937
-
938
- end
939
- -------------------------------------------------
940
-
941
- 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.
942
-
943
- Here's the content of the +invite+ fixture:
944
-
945
- -------------------------------------------------
946
- Hi friend@example.com,
947
-
948
- You have been invited.
949
-
950
- Cheers!
951
- -------------------------------------------------
952
-
953
- 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+).
954
-
955
- However often in unit tests, mails will not actually be sent, simply constructed, as in the example above, where the precise content of the email is checked against what it should be.
956
-
957
- === Functional Testing ===
958
-
959
- Functional testing for mailers involves more than just checking that the email body, recipients and so forth are correct. In functional mail tests you call the mail deliver methods and check that the appropriate emails have been appended to the delivery list. It is fairly safe to assume that the deliver methods themselves do their job You are probably more interested in is whether your own business logic is sending emails when you expect them to got out. For example, you can check that the invite friend operation is sending an email appropriately:
960
-
961
- [source, ruby]
962
- ----------------------------------------------------------------
963
- require 'test_helper'
964
-
965
- class UserControllerTest < ActionController::TestCase
966
- def test_invite_friend
967
- assert_difference 'ActionMailer::Base.deliveries.size', +1 do
968
- post :invite_friend, :email => 'friend@example.com'
969
- end
970
- invite_email = ActionMailer::Base.deliveries.first
971
-
972
- assert_equal invite_email.subject, "You have been invited by me@example.com"
973
- assert_equal invite_email.to[0], 'friend@example.com'
974
- assert_match /Hi friend@example.com/, invite_email.body
975
- end
976
- end
977
- ----------------------------------------------------------------
978
-
979
- == Other Testing Approaches
980
-
981
- 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:
982
-
983
- * link:http://avdi.org/projects/nulldb/[NullDB], a way to speed up testing by avoiding database use.
984
- * link:http://github.com/thoughtbot/factory_girl/tree/master[Factory Girl], as replacement for fixtures.
985
- * link:http://www.thoughtbot.com/projects/shoulda[Shoulda], an extension to +test/unit+ with additional helpers, macros, and assertions.
986
- * link: http://rspec.info/[RSpec], a behavior-driven development framework
987
-
988
- == Changelog ==
989
-
990
- http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/8[Lighthouse ticket]
991
-
992
- * November 13, 2008: Revised based on feedback from Pratik Naik by link:../authors.html#asurve[Akshay Surve] (not yet approved for publication)
993
- * October 14, 2008: Edit and formatting pass by link:../authors.html#mgunderloy[Mike Gunderloy] (not yet approved for publication)
994
- * October 12, 2008: First draft by link:../authors.html#asurve[Akshay Surve] (not yet approved for publication)
995
-