railties 3.0.0.beta

Sign up to get free protection for your applications and to get access to all the features.
Files changed (334) hide show
  1. data/CHANGELOG +2201 -0
  2. data/README +286 -0
  3. data/bin/rails +11 -0
  4. data/builtin/rails_info/rails/info.rb +147 -0
  5. data/builtin/rails_info/rails/info_controller.rb +15 -0
  6. data/builtin/rails_info/rails/info_helper.rb +2 -0
  7. data/builtin/routes.rb +3 -0
  8. data/guides/files/javascripts/code_highlighter.js +188 -0
  9. data/guides/files/javascripts/guides.js +7 -0
  10. data/guides/files/javascripts/highlighters.js +90 -0
  11. data/guides/files/stylesheets/main.css +441 -0
  12. data/guides/files/stylesheets/print.css +52 -0
  13. data/guides/files/stylesheets/reset.css +43 -0
  14. data/guides/files/stylesheets/style.css +13 -0
  15. data/guides/files/stylesheets/syntax.css +31 -0
  16. data/guides/images/belongs_to.png +0 -0
  17. data/guides/images/book_icon.gif +0 -0
  18. data/guides/images/bullet.gif +0 -0
  19. data/guides/images/chapters_icon.gif +0 -0
  20. data/guides/images/check_bullet.gif +0 -0
  21. data/guides/images/credits_pic_blank.gif +0 -0
  22. data/guides/images/csrf.png +0 -0
  23. data/guides/images/customized_error_messages.png +0 -0
  24. data/guides/images/error_messages.png +0 -0
  25. data/guides/images/feature_tile.gif +0 -0
  26. data/guides/images/footer_tile.gif +0 -0
  27. data/guides/images/fxn.png +0 -0
  28. data/guides/images/grey_bullet.gif +0 -0
  29. data/guides/images/habtm.png +0 -0
  30. data/guides/images/has_many.png +0 -0
  31. data/guides/images/has_many_through.png +0 -0
  32. data/guides/images/has_one.png +0 -0
  33. data/guides/images/has_one_through.png +0 -0
  34. data/guides/images/header_backdrop.png +0 -0
  35. data/guides/images/header_tile.gif +0 -0
  36. data/guides/images/i18n/demo_localized_pirate.png +0 -0
  37. data/guides/images/i18n/demo_translated_en.png +0 -0
  38. data/guides/images/i18n/demo_translated_pirate.png +0 -0
  39. data/guides/images/i18n/demo_translation_missing.png +0 -0
  40. data/guides/images/i18n/demo_untranslated.png +0 -0
  41. data/guides/images/icons/README +5 -0
  42. data/guides/images/icons/callouts/1.png +0 -0
  43. data/guides/images/icons/callouts/10.png +0 -0
  44. data/guides/images/icons/callouts/11.png +0 -0
  45. data/guides/images/icons/callouts/12.png +0 -0
  46. data/guides/images/icons/callouts/13.png +0 -0
  47. data/guides/images/icons/callouts/14.png +0 -0
  48. data/guides/images/icons/callouts/15.png +0 -0
  49. data/guides/images/icons/callouts/2.png +0 -0
  50. data/guides/images/icons/callouts/3.png +0 -0
  51. data/guides/images/icons/callouts/4.png +0 -0
  52. data/guides/images/icons/callouts/5.png +0 -0
  53. data/guides/images/icons/callouts/6.png +0 -0
  54. data/guides/images/icons/callouts/7.png +0 -0
  55. data/guides/images/icons/callouts/8.png +0 -0
  56. data/guides/images/icons/callouts/9.png +0 -0
  57. data/guides/images/icons/caution.png +0 -0
  58. data/guides/images/icons/example.png +0 -0
  59. data/guides/images/icons/home.png +0 -0
  60. data/guides/images/icons/important.png +0 -0
  61. data/guides/images/icons/next.png +0 -0
  62. data/guides/images/icons/note.png +0 -0
  63. data/guides/images/icons/prev.png +0 -0
  64. data/guides/images/icons/tip.png +0 -0
  65. data/guides/images/icons/up.png +0 -0
  66. data/guides/images/icons/warning.png +0 -0
  67. data/guides/images/nav_arrow.gif +0 -0
  68. data/guides/images/polymorphic.png +0 -0
  69. data/guides/images/posts_index.png +0 -0
  70. data/guides/images/rails_guides_logo.gif +0 -0
  71. data/guides/images/rails_logo_remix.gif +0 -0
  72. data/guides/images/rails_welcome.png +0 -0
  73. data/guides/images/session_fixation.png +0 -0
  74. data/guides/images/tab_grey.gif +0 -0
  75. data/guides/images/tab_info.gif +0 -0
  76. data/guides/images/tab_note.gif +0 -0
  77. data/guides/images/tab_red.gif +0 -0
  78. data/guides/images/tab_yellow.gif +0 -0
  79. data/guides/images/tab_yellow.png +0 -0
  80. data/guides/images/validation_error_messages.png +0 -0
  81. data/guides/rails_guides.rb +44 -0
  82. data/guides/rails_guides/generator.rb +178 -0
  83. data/guides/rails_guides/helpers.rb +34 -0
  84. data/guides/rails_guides/indexer.rb +55 -0
  85. data/guides/rails_guides/levenshtein.rb +31 -0
  86. data/guides/rails_guides/textile_extensions.rb +41 -0
  87. data/guides/source/2_2_release_notes.textile +422 -0
  88. data/guides/source/2_3_release_notes.textile +610 -0
  89. data/guides/source/3_0_release_notes.textile +560 -0
  90. data/guides/source/action_controller_overview.textile +783 -0
  91. data/guides/source/action_mailer_basics.textile +437 -0
  92. data/guides/source/action_view_overview.textile +1481 -0
  93. data/guides/source/active_record_basics.textile +204 -0
  94. data/guides/source/active_record_querying.textile +961 -0
  95. data/guides/source/active_support_core_extensions.textile +1835 -0
  96. data/guides/source/activerecord_validations_callbacks.textile +1127 -0
  97. data/guides/source/ajax_on_rails.textile +342 -0
  98. data/guides/source/association_basics.textile +1816 -0
  99. data/guides/source/caching_with_rails.textile +390 -0
  100. data/guides/source/command_line.textile +589 -0
  101. data/guides/source/configuring.textile +290 -0
  102. data/guides/source/contribute.textile +71 -0
  103. data/guides/source/contributing_to_rails.textile +272 -0
  104. data/guides/source/credits.textile.erb +52 -0
  105. data/guides/source/debugging_rails_applications.textile +709 -0
  106. data/guides/source/form_helpers.textile +768 -0
  107. data/guides/source/generators.textile +378 -0
  108. data/guides/source/getting_started.textile +1310 -0
  109. data/guides/source/i18n.textile +879 -0
  110. data/guides/source/index.textile.erb +124 -0
  111. data/guides/source/layout.html.erb +103 -0
  112. data/guides/source/layouts_and_rendering.textile +979 -0
  113. data/guides/source/migrations.textile +591 -0
  114. data/guides/source/nested_model_forms.textile +222 -0
  115. data/guides/source/performance_testing.textile +531 -0
  116. data/guides/source/plugins.textile +1512 -0
  117. data/guides/source/rails_application_templates.textile +238 -0
  118. data/guides/source/rails_on_rack.textile +306 -0
  119. data/guides/source/routing.textile +903 -0
  120. data/guides/source/security.textile +984 -0
  121. data/guides/source/testing.textile +946 -0
  122. data/lib/generators/erb.rb +8 -0
  123. data/lib/generators/erb/controller/controller_generator.rb +21 -0
  124. data/lib/generators/erb/controller/templates/view.html.erb +2 -0
  125. data/lib/generators/erb/mailer/mailer_generator.rb +20 -0
  126. data/lib/generators/erb/mailer/templates/view.text.erb +3 -0
  127. data/lib/generators/erb/scaffold/scaffold_generator.rb +53 -0
  128. data/lib/generators/erb/scaffold/templates/_form.html.erb +13 -0
  129. data/lib/generators/erb/scaffold/templates/edit.html.erb +6 -0
  130. data/lib/generators/erb/scaffold/templates/index.html.erb +27 -0
  131. data/lib/generators/erb/scaffold/templates/layout.html.erb +16 -0
  132. data/lib/generators/erb/scaffold/templates/new.html.erb +5 -0
  133. data/lib/generators/erb/scaffold/templates/show.html.erb +10 -0
  134. data/lib/generators/rails/app/USAGE +9 -0
  135. data/lib/generators/rails/app/app_generator.rb +262 -0
  136. data/lib/generators/rails/app/templates/Gemfile +34 -0
  137. data/lib/generators/rails/app/templates/README +243 -0
  138. data/lib/generators/rails/app/templates/Rakefile +10 -0
  139. data/lib/generators/rails/app/templates/app/controllers/application_controller.rb +3 -0
  140. data/lib/generators/rails/app/templates/app/helpers/application_helper.rb +2 -0
  141. data/lib/generators/rails/app/templates/app/models/.empty_directory +0 -0
  142. data/lib/generators/rails/app/templates/app/views/layouts/.empty_directory +0 -0
  143. data/lib/generators/rails/app/templates/config.ru +4 -0
  144. data/lib/generators/rails/app/templates/config/application.rb +51 -0
  145. data/lib/generators/rails/app/templates/config/boot.rb +17 -0
  146. data/lib/generators/rails/app/templates/config/databases/frontbase.yml +28 -0
  147. data/lib/generators/rails/app/templates/config/databases/ibm_db.yml +71 -0
  148. data/lib/generators/rails/app/templates/config/databases/mysql.yml +60 -0
  149. data/lib/generators/rails/app/templates/config/databases/oracle.yml +39 -0
  150. data/lib/generators/rails/app/templates/config/databases/postgresql.yml +51 -0
  151. data/lib/generators/rails/app/templates/config/databases/sqlite3.yml +22 -0
  152. data/lib/generators/rails/app/templates/config/environment.rb +5 -0
  153. data/lib/generators/rails/app/templates/config/environments/development.rb.tt +19 -0
  154. data/lib/generators/rails/app/templates/config/environments/production.rb.tt +33 -0
  155. data/lib/generators/rails/app/templates/config/environments/test.rb.tt +29 -0
  156. data/lib/generators/rails/app/templates/config/initializers/backtrace_silencers.rb +7 -0
  157. data/lib/generators/rails/app/templates/config/initializers/cookie_verification_secret.rb.tt +7 -0
  158. data/lib/generators/rails/app/templates/config/initializers/inflections.rb +10 -0
  159. data/lib/generators/rails/app/templates/config/initializers/mime_types.rb +5 -0
  160. data/lib/generators/rails/app/templates/config/initializers/session_store.rb.tt +15 -0
  161. data/lib/generators/rails/app/templates/config/locales/en.yml +5 -0
  162. data/lib/generators/rails/app/templates/config/routes.rb +58 -0
  163. data/lib/generators/rails/app/templates/db/seeds.rb +7 -0
  164. data/lib/generators/rails/app/templates/doc/README_FOR_APP +2 -0
  165. data/lib/generators/rails/app/templates/gitignore +4 -0
  166. data/lib/generators/rails/app/templates/public/404.html +26 -0
  167. data/lib/generators/rails/app/templates/public/422.html +26 -0
  168. data/lib/generators/rails/app/templates/public/500.html +26 -0
  169. data/lib/generators/rails/app/templates/public/favicon.ico +0 -0
  170. data/lib/generators/rails/app/templates/public/images/rails.png +0 -0
  171. data/lib/generators/rails/app/templates/public/index.html +278 -0
  172. data/lib/generators/rails/app/templates/public/javascripts/application.js +2 -0
  173. data/lib/generators/rails/app/templates/public/javascripts/controls.js +963 -0
  174. data/lib/generators/rails/app/templates/public/javascripts/dragdrop.js +973 -0
  175. data/lib/generators/rails/app/templates/public/javascripts/effects.js +1128 -0
  176. data/lib/generators/rails/app/templates/public/javascripts/prototype.js +4320 -0
  177. data/lib/generators/rails/app/templates/public/javascripts/rails.js +110 -0
  178. data/lib/generators/rails/app/templates/public/robots.txt +5 -0
  179. data/lib/generators/rails/app/templates/public/stylesheets/.empty_directory +0 -0
  180. data/lib/generators/rails/app/templates/script/rails +9 -0
  181. data/lib/generators/rails/app/templates/test/fixtures/.empty_directory +0 -0
  182. data/lib/generators/rails/app/templates/test/functional/.empty_directory +0 -0
  183. data/lib/generators/rails/app/templates/test/integration/.empty_directory +0 -0
  184. data/lib/generators/rails/app/templates/test/performance/browsing_test.rb +9 -0
  185. data/lib/generators/rails/app/templates/test/test_helper.rb +13 -0
  186. data/lib/generators/rails/app/templates/test/unit/.empty_directory +0 -0
  187. data/lib/generators/rails/controller/USAGE +18 -0
  188. data/lib/generators/rails/controller/controller_generator.rb +14 -0
  189. data/lib/generators/rails/controller/templates/controller.rb +7 -0
  190. data/lib/generators/rails/generator/USAGE +11 -0
  191. data/lib/generators/rails/generator/generator_generator.rb +25 -0
  192. data/lib/generators/rails/generator/templates/%file_name%_generator.rb.tt +5 -0
  193. data/lib/generators/rails/generator/templates/USAGE.tt +8 -0
  194. data/lib/generators/rails/generator/templates/templates/.empty_directory +0 -0
  195. data/lib/generators/rails/helper/USAGE +17 -0
  196. data/lib/generators/rails/helper/helper_generator.rb +13 -0
  197. data/lib/generators/rails/helper/templates/helper.rb +2 -0
  198. data/lib/generators/rails/integration_test/USAGE +10 -0
  199. data/lib/generators/rails/integration_test/integration_test_generator.rb +7 -0
  200. data/lib/generators/rails/mailer/USAGE +15 -0
  201. data/lib/generators/rails/mailer/mailer_generator.rb +14 -0
  202. data/lib/generators/rails/mailer/templates/mailer.rb +16 -0
  203. data/lib/generators/rails/metal/USAGE +8 -0
  204. data/lib/generators/rails/metal/metal_generator.rb +11 -0
  205. data/lib/generators/rails/metal/templates/metal.rb +12 -0
  206. data/lib/generators/rails/migration/USAGE +29 -0
  207. data/lib/generators/rails/migration/migration_generator.rb +8 -0
  208. data/lib/generators/rails/model/USAGE +30 -0
  209. data/lib/generators/rails/model/model_generator.rb +8 -0
  210. data/lib/generators/rails/model_subclass/model_subclass_generator.rb +12 -0
  211. data/lib/generators/rails/observer/USAGE +12 -0
  212. data/lib/generators/rails/observer/observer_generator.rb +7 -0
  213. data/lib/generators/rails/performance_test/USAGE +10 -0
  214. data/lib/generators/rails/performance_test/performance_test_generator.rb +7 -0
  215. data/lib/generators/rails/plugin/USAGE +13 -0
  216. data/lib/generators/rails/plugin/plugin_generator.rb +47 -0
  217. data/lib/generators/rails/plugin/templates/MIT-LICENSE.tt +20 -0
  218. data/lib/generators/rails/plugin/templates/README.tt +13 -0
  219. data/lib/generators/rails/plugin/templates/Rakefile.tt +10 -0
  220. data/lib/generators/rails/plugin/templates/init.rb +1 -0
  221. data/lib/generators/rails/plugin/templates/install.rb +1 -0
  222. data/lib/generators/rails/plugin/templates/lib/%file_name%.rb.tt +1 -0
  223. data/lib/generators/rails/plugin/templates/lib/tasks/%file_name%_tasks.rake.tt +4 -0
  224. data/lib/generators/rails/plugin/templates/uninstall.rb +1 -0
  225. data/lib/generators/rails/resource/USAGE +23 -0
  226. data/lib/generators/rails/resource/resource_generator.rb +34 -0
  227. data/lib/generators/rails/scaffold/USAGE +29 -0
  228. data/lib/generators/rails/scaffold/scaffold_generator.rb +13 -0
  229. data/lib/generators/rails/scaffold_controller/USAGE +20 -0
  230. data/lib/generators/rails/scaffold_controller/scaffold_controller_generator.rb +27 -0
  231. data/lib/generators/rails/scaffold_controller/templates/controller.rb +85 -0
  232. data/lib/generators/rails/session_migration/USAGE +8 -0
  233. data/lib/generators/rails/session_migration/session_migration_generator.rb +8 -0
  234. data/lib/generators/rails/stylesheets/USAGE +5 -0
  235. data/lib/generators/rails/stylesheets/stylesheets_generator.rb +9 -0
  236. data/lib/generators/rails/stylesheets/templates/scaffold.css +61 -0
  237. data/lib/generators/test_unit.rb +8 -0
  238. data/lib/generators/test_unit/controller/controller_generator.rb +14 -0
  239. data/lib/generators/test_unit/controller/templates/functional_test.rb +8 -0
  240. data/lib/generators/test_unit/helper/helper_generator.rb +13 -0
  241. data/lib/generators/test_unit/helper/templates/helper_test.rb +4 -0
  242. data/lib/generators/test_unit/integration/integration_generator.rb +13 -0
  243. data/lib/generators/test_unit/integration/templates/integration_test.rb +10 -0
  244. data/lib/generators/test_unit/mailer/mailer_generator.rb +21 -0
  245. data/lib/generators/test_unit/mailer/templates/fixture +3 -0
  246. data/lib/generators/test_unit/mailer/templates/functional_test.rb +22 -0
  247. data/lib/generators/test_unit/model/model_generator.rb +24 -0
  248. data/lib/generators/test_unit/model/templates/fixtures.yml +23 -0
  249. data/lib/generators/test_unit/model/templates/unit_test.rb +8 -0
  250. data/lib/generators/test_unit/observer/observer_generator.rb +13 -0
  251. data/lib/generators/test_unit/observer/templates/unit_test.rb +8 -0
  252. data/lib/generators/test_unit/performance/performance_generator.rb +13 -0
  253. data/lib/generators/test_unit/performance/templates/performance_test.rb +9 -0
  254. data/lib/generators/test_unit/plugin/plugin_generator.rb +13 -0
  255. data/lib/generators/test_unit/plugin/templates/%file_name%_test.rb.tt +8 -0
  256. data/lib/generators/test_unit/plugin/templates/test_helper.rb +3 -0
  257. data/lib/generators/test_unit/scaffold/scaffold_generator.rb +18 -0
  258. data/lib/generators/test_unit/scaffold/templates/functional_test.rb +47 -0
  259. data/lib/rails.rb +95 -0
  260. data/lib/rails/all.rb +14 -0
  261. data/lib/rails/application.rb +125 -0
  262. data/lib/rails/application/bootstrap.rb +85 -0
  263. data/lib/rails/application/configurable.rb +19 -0
  264. data/lib/rails/application/configuration.rb +86 -0
  265. data/lib/rails/application/finisher.rb +49 -0
  266. data/lib/rails/application/metal_loader.rb +50 -0
  267. data/lib/rails/application/railties.rb +31 -0
  268. data/lib/rails/application/routes_reloader.rb +46 -0
  269. data/lib/rails/backtrace_cleaner.rb +54 -0
  270. data/lib/rails/code_statistics.rb +107 -0
  271. data/lib/rails/commands.rb +72 -0
  272. data/lib/rails/commands/application.rb +13 -0
  273. data/lib/rails/commands/console.rb +55 -0
  274. data/lib/rails/commands/dbconsole.rb +104 -0
  275. data/lib/rails/commands/destroy.rb +9 -0
  276. data/lib/rails/commands/generate.rb +9 -0
  277. data/lib/rails/commands/performance/benchmarker.rb +23 -0
  278. data/lib/rails/commands/performance/profiler.rb +46 -0
  279. data/lib/rails/commands/plugin.rb +542 -0
  280. data/lib/rails/commands/runner.rb +51 -0
  281. data/lib/rails/commands/server.rb +75 -0
  282. data/lib/rails/commands/update.rb +9 -0
  283. data/lib/rails/configuration.rb +191 -0
  284. data/lib/rails/console/app.rb +33 -0
  285. data/lib/rails/console/helpers.rb +5 -0
  286. data/lib/rails/console/sandbox.rb +6 -0
  287. data/lib/rails/deprecation.rb +62 -0
  288. data/lib/rails/dispatcher.rb +24 -0
  289. data/lib/rails/engine.rb +130 -0
  290. data/lib/rails/engine/configurable.rb +25 -0
  291. data/lib/rails/engine/configuration.rb +49 -0
  292. data/lib/rails/generators.rb +289 -0
  293. data/lib/rails/generators/actions.rb +309 -0
  294. data/lib/rails/generators/active_model.rb +78 -0
  295. data/lib/rails/generators/base.rb +362 -0
  296. data/lib/rails/generators/generated_attribute.rb +48 -0
  297. data/lib/rails/generators/migration.rb +64 -0
  298. data/lib/rails/generators/named_base.rb +95 -0
  299. data/lib/rails/generators/resource_helpers.rb +80 -0
  300. data/lib/rails/generators/test_case.rb +239 -0
  301. data/lib/rails/initializable.rb +97 -0
  302. data/lib/rails/paths.rb +144 -0
  303. data/lib/rails/performance_test_help.rb +3 -0
  304. data/lib/rails/plugin.rb +64 -0
  305. data/lib/rails/rack.rb +8 -0
  306. data/lib/rails/rack/debugger.rb +23 -0
  307. data/lib/rails/rack/log_tailer.rb +33 -0
  308. data/lib/rails/rack/logger.rb +34 -0
  309. data/lib/rails/rack/static.rb +5 -0
  310. data/lib/rails/railtie.rb +74 -0
  311. data/lib/rails/railtie/configurable.rb +23 -0
  312. data/lib/rails/railtie/configuration.rb +9 -0
  313. data/lib/rails/railties_path.rb +1 -0
  314. data/lib/rails/ruby_version_check.rb +10 -0
  315. data/lib/rails/rubyprof_ext.rb +35 -0
  316. data/lib/rails/source_annotation_extractor.rb +102 -0
  317. data/lib/rails/subscriber.rb +108 -0
  318. data/lib/rails/subscriber/test_helper.rb +98 -0
  319. data/lib/rails/tasks.rb +16 -0
  320. data/lib/rails/tasks/annotations.rake +20 -0
  321. data/lib/rails/tasks/documentation.rake +96 -0
  322. data/lib/rails/tasks/framework.rake +69 -0
  323. data/lib/rails/tasks/log.rake +9 -0
  324. data/lib/rails/tasks/middleware.rake +7 -0
  325. data/lib/rails/tasks/misc.rake +71 -0
  326. data/lib/rails/tasks/routes.rake +17 -0
  327. data/lib/rails/tasks/statistics.rake +16 -0
  328. data/lib/rails/tasks/tmp.rake +37 -0
  329. data/lib/rails/test_help.rb +30 -0
  330. data/lib/rails/test_unit/railtie.rb +17 -0
  331. data/lib/rails/test_unit/testing.rake +130 -0
  332. data/lib/rails/version.rb +9 -0
  333. data/lib/rails/webrick_server.rb +156 -0
  334. metadata +427 -0
@@ -0,0 +1,946 @@
1
+ h2. A Guide to Testing Rails Applications
2
+
3
+ This guide covers built-in mechanisms offered by Rails to test your application. By referring to this guide, you will be able to:
4
+
5
+ * Understand Rails testing terminology
6
+ * Write unit, functional and integration tests for your application
7
+ * Identify other popular testing approaches and plugins
8
+
9
+ This guide won't teach you to write a Rails application; it assumes basic familiarity with the Rails way of doing things.
10
+
11
+ endprologue.
12
+
13
+ h3. Why Write Tests for your Rails Applications?
14
+
15
+ * 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.
16
+ * By simply running your Rails tests you can ensure your code adheres to the desired functionality even after some major code refactoring.
17
+ * Rails tests can also simulate browser requests and thus you can test your application's response without having to test it through your browser.
18
+
19
+ h3. Introduction to Testing
20
+
21
+ 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.
22
+
23
+ h4. The Three Environments
24
+
25
+ Every Rails application you build has 3 sides: a side for production, a side for development, and a side for testing.
26
+
27
+ 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:
28
+
29
+ * production
30
+ * development
31
+ * test
32
+
33
+ This allows you to set up and interact with test data without any danger of your tests altering data from your production environment.
34
+
35
+ 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?
36
+
37
+ 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+.
38
+
39
+ h4. Rails Sets up for Testing from the Word Go
40
+
41
+ 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:
42
+
43
+ <shell>
44
+ $ ls -F test/
45
+
46
+ fixtures/ functional/ integration/ test_helper.rb unit/
47
+ </shell>
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
+ h4. 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
+ h5. 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
+ h5. YAML
62
+
63
+ YAML-formatted fixtures are a very human-friendly way to describe your sample data. These types of fixtures have the *.yml* file extension (as in +users.yml+).
64
+
65
+ Here's a sample YAML fixture file:
66
+
67
+ <yaml>
68
+ # low & behold! I am a YAML comment!
69
+ david:
70
+ name: David Heinemeier Hansson
71
+ birthday: 1979-10-15
72
+ profession: Systems development
73
+
74
+ steve:
75
+ name: Steve Ross Kellock
76
+ birthday: 1974-09-27
77
+ profession: guy with keyboard
78
+ </yaml>
79
+
80
+ 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.
81
+
82
+ h5. ERb'in It Up
83
+
84
+ 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.
85
+
86
+ <erb>
87
+ <% earth_size = 20 -%>
88
+ mercury:
89
+ size: <%= earth_size / 50 %>
90
+ brightest_on: <%= 113.days.ago.to_s(:db) %>
91
+
92
+ venus:
93
+ size: <%= earth_size / 2 %>
94
+ brightest_on: <%= 67.days.ago.to_s(:db) %>
95
+
96
+ mars:
97
+ size: <%= earth_size - 69 %>
98
+ brightest_on: <%= 13.days.from_now.to_s(:db) %>
99
+ </erb>
100
+
101
+ Anything encased within the
102
+
103
+ <erb>
104
+ <% %>
105
+ </erb>
106
+
107
+ 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.
108
+
109
+ h5. Fixtures in Action
110
+
111
+ Rails by default automatically loads all fixtures from the 'test/fixtures' folder for your unit and functional 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
+ h5. Hashes with Special Powers
118
+
119
+ 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:
120
+
121
+ <ruby>
122
+ # this will return the Hash for the fixture named david
123
+ users(:david)
124
+
125
+ # this will return the property for david called id
126
+ users(:david).id
127
+ </ruby>
128
+
129
+ Fixtures can also transform themselves into the form of the original class. Thus, you can get at the methods only available to that class.
130
+
131
+ <ruby>
132
+ # using the find method, we grab the "real" david as a User
133
+ david = users(:david).find
134
+
135
+ # and now we have access to methods only available to a User class
136
+ email(david.girlfriend.email, david.location_tonight)
137
+ </ruby>
138
+
139
+ h3. Unit Testing your Models
140
+
141
+ In Rails, unit tests are what you write to test your models.
142
+
143
+ 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 would be supplementing it with additional examples where necessary.
144
+
145
+ NOTE: For more information on Rails _scaffolding_, refer to "Getting Started with Rails":getting_started.html
146
+
147
+ When you use +script/generate scaffold+, for a resource among other things it creates a test stub in the +test/unit+ folder:
148
+
149
+ <pre>
150
+ $ script/generate scaffold post title:string body:text
151
+ ...
152
+ create app/models/post.rb
153
+ create test/unit/post_test.rb
154
+ create test/fixtures/posts.yml
155
+ ...
156
+ </pre>
157
+
158
+ The default test stub in +test/unit/post_test.rb+ looks like this:
159
+
160
+ <ruby>
161
+ require 'test_helper'
162
+
163
+ class PostTest < ActiveSupport::TestCase
164
+ # Replace this with your real tests.
165
+ test "the truth" do
166
+ assert true
167
+ end
168
+ end
169
+ </ruby>
170
+
171
+ A line by line examination of this file will help get you oriented to Rails testing code and terminology.
172
+
173
+ <ruby>
174
+ require 'test_helper'
175
+ </ruby>
176
+
177
+ 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.
178
+
179
+ <ruby>
180
+ class PostTest < ActiveSupport::TestCase
181
+ </ruby>
182
+
183
+ 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.
184
+
185
+ <ruby>
186
+ def test_truth
187
+ </ruby>
188
+
189
+ Any method defined within a +Test::Unit+ test case that begins with +test+ (case sensitive) is simply called a test. So, +test_password+, +test_valid_password+ and +testValidPassword+ all are legal test names and are run automatically when the test case is run.
190
+
191
+ Rails adds a +test+ method that takes a test name and a block. It generates a normal +Test::Unit+ test with method names prefixed with +test_+.
192
+
193
+ <ruby>
194
+ test "the truth" do
195
+ # ...
196
+ end
197
+ </ruby>
198
+
199
+ This makes test names more readable by replacing underscores with regular language.
200
+
201
+ <ruby>
202
+ assert true
203
+ </ruby>
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
+ h4. Preparing your 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
+ <shell>
219
+ $ rake db:migrate
220
+ ...
221
+ $ rake db:test:load
222
+ </shell>
223
+
224
+ Above +rake db:migrate+ runs any pending migrations on the _development_ 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.
225
+
226
+ NOTE: +db:test:prepare+ will fail with an error if db/schema.rb doesn't exists.
227
+
228
+ h5. Rake Tasks for Preparing your Application for Testing
229
+
230
+ |_.Tasks |_.Description|
231
+ |+rake db:test:clone+ |Recreate the test database from the current environment's database schema|
232
+ |+rake db:test:clone_structure+ |Recreate the test databases from the development structure|
233
+ |+rake db:test:load+ |Recreate the test database from the current +schema.rb+|
234
+ |+rake db:test:prepare+ |Check for pending migrations and load the test schema|
235
+ |+rake db:test:purge+ |Empty the test database.|
236
+
237
+ TIP: You can see all these rake tasks and their descriptions by running +rake --tasks --describe+
238
+
239
+ h4. Running Tests
240
+
241
+ Running a test is as simple as invoking the file containing the test cases through Ruby:
242
+
243
+ <shell>
244
+ $ cd test
245
+ $ ruby unit/post_test.rb
246
+
247
+ Loaded suite unit/post_test
248
+ Started
249
+ .
250
+ Finished in 0.023513 seconds.
251
+
252
+ 1 tests, 1 assertions, 0 failures, 0 errors
253
+ </shell>
254
+
255
+ This will run all the test methods from the test case.
256
+
257
+ You can also run a particular test method from the test case by using the +-n+ switch with the +test method name+.
258
+
259
+ <pre>
260
+ $ ruby unit/post_test.rb -n test_truth
261
+
262
+ Loaded suite unit/post_test
263
+ Started
264
+ .
265
+ Finished in 0.023513 seconds.
266
+
267
+ 1 tests, 1 assertions, 0 failures, 0 errors
268
+ </pre>
269
+
270
+ 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.
271
+
272
+ To see how a test failure is reported, you can add a failing test to the +post_test.rb+ test case.
273
+
274
+ <ruby>
275
+ test "should not save post without title" do
276
+ post = Post.new
277
+ assert !post.save
278
+ end
279
+ </ruby>
280
+
281
+ Let us run this newly added test.
282
+
283
+ <pre>
284
+ $ ruby unit/post_test.rb -n test_should_not_save_post_without_title
285
+ Loaded suite -e
286
+ Started
287
+ F
288
+ Finished in 0.102072 seconds.
289
+
290
+ 1) Failure:
291
+ test_should_not_save_post_without_title(PostTest) [/test/unit/post_test.rb:6]:
292
+ <false> is not true.
293
+
294
+ 1 tests, 1 assertions, 1 failures, 0 errors
295
+ </pre>
296
+
297
+ 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:
298
+
299
+ <ruby>
300
+ test "should not save post without title" do
301
+ post = Post.new
302
+ assert !post.save, "Saved the post without a title"
303
+ end
304
+ </ruby>
305
+
306
+ Running this test shows the friendlier assertion message:
307
+
308
+ <pre>
309
+ 1) Failure:
310
+ test_should_not_save_post_without_title(PostTest) [/test/unit/post_test.rb:6]:
311
+ Saved the post without a title.
312
+ <false> is not true.
313
+ </pre>
314
+
315
+ Now to get this test to pass we can add a model level validation for the _title_ field.
316
+
317
+ <ruby>
318
+ class Post < ActiveRecord::Base
319
+ validates_presence_of :title
320
+ end
321
+ </ruby>
322
+
323
+ Now the test should pass. Let us verify by running the test again:
324
+
325
+ <pre>
326
+ $ ruby unit/post_test.rb -n test_should_not_save_post_without_title
327
+ Loaded suite unit/post_test
328
+ Started
329
+ .
330
+ Finished in 0.193608 seconds.
331
+
332
+ 1 tests, 1 assertions, 0 failures, 0 errors
333
+ </pre>
334
+
335
+ 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).
336
+
337
+ 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.
338
+
339
+ To see how an error gets reported, here's a test containing an error:
340
+
341
+ <ruby>
342
+ test "should report error" do
343
+ # some_undefined_variable is not defined elsewhere in the test case
344
+ some_undefined_variable
345
+ assert true
346
+ end
347
+ </ruby>
348
+
349
+ Now you can see even more output in the console from running the tests:
350
+
351
+ <pre>
352
+ $ ruby unit/post_test.rb -n test_should_report_error
353
+ Loaded suite -e
354
+ Started
355
+ E
356
+ Finished in 0.082603 seconds.
357
+
358
+ 1) Error:
359
+ test_should_report_error(PostTest):
360
+ NameError: undefined local variable or method `some_undefined_variable' for #<PostTest:0x249d354>
361
+ /test/unit/post_test.rb:6:in `test_should_report_error'
362
+
363
+ 1 tests, 0 assertions, 0 failures, 1 errors
364
+ </pre>
365
+
366
+ Notice the 'E' in the output. It denotes a test with error.
367
+
368
+ 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.
369
+
370
+ h4. What to Include in Your Unit Tests
371
+
372
+ 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.
373
+
374
+ h4. Assertions Available
375
+
376
+ 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.
377
+
378
+ 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.
379
+
380
+ |_.Assertion |_.Purpose|
381
+ |+assert( boolean, [msg] )+ |Ensures that the object/expression is true.|
382
+ |+assert_equal( obj1, obj2, [msg] )+ |Ensures that +obj1 == obj2+ is true.|
383
+ |+assert_not_equal( obj1, obj2, [msg] )+ |Ensures that +obj1 == obj2+ is false.|
384
+ |+assert_same( obj1, obj2, [msg] )+ |Ensures that +obj1.equal?(obj2)+ is true.|
385
+ |+assert_not_same( obj1, obj2, [msg] )+ |Ensures that +obj1.equal?(obj2)+ is false.|
386
+ |+assert_nil( obj, [msg] )+ |Ensures that +obj.nil?+ is true.|
387
+ |+assert_not_nil( obj, [msg] )+ |Ensures that +obj.nil?+ is false.|
388
+ |+assert_match( regexp, string, [msg] )+ |Ensures that a string matches the regular expression.|
389
+ |+assert_no_match( regexp, string, [msg] )+ |Ensures that a string doesn't matches the regular expression.|
390
+ |+assert_in_delta( expecting, actual, delta, [msg] )+ |Ensures that the numbers +expecting+ and +actual+ are within +delta+ of each other.|
391
+ |+assert_throws( symbol, [msg] ) { block }+ |Ensures that the given block throws the symbol.|
392
+ |+assert_raise( exception1, exception2, ... ) { block }+ |Ensures that the given block raises one of the given exceptions.|
393
+ |+assert_nothing_raised( exception1, exception2, ... ) { block }+ |Ensures that the given block doesn't raise one of the given exceptions.|
394
+ |+assert_instance_of( class, obj, [msg] )+ |Ensures that +obj+ is of the +class+ type.|
395
+ |+assert_kind_of( class, obj, [msg] )+ |Ensures that +obj+ is or descends from +class+.|
396
+ |+assert_respond_to( obj, symbol, [msg] )+ |Ensures that +obj+ has a method called +symbol+.|
397
+ |+assert_operator( obj1, operator, obj2, [msg] )+ |Ensures that +obj1.operator(obj2)+ is true.|
398
+ |+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?|
399
+ |+flunk( [msg] )+ |Ensures failure. This is useful to explicitly mark a test that isn't finished yet.|
400
+
401
+ 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.
402
+
403
+ NOTE: Creating your own assertions is an advanced topic that we won't cover in this tutorial.
404
+
405
+ h4. Rails Specific Assertions
406
+
407
+ Rails adds some custom assertions of its own to the +test/unit+ framework:
408
+
409
+ NOTE: +assert_valid(record)+ has been deprecated. Please use +assert(record.valid?)+ instead.
410
+
411
+ |_.Assertion |_.Purpose|
412
+ |+assert_valid(record)+ |Ensures that the passed record is valid by Active Record standards and returns any error messages if it is not.|
413
+ |+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.|
414
+ |+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.|
415
+ |+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.|
416
+ |+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.|
417
+ |+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|
418
+ |+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.|
419
+ |+assert_template(expected = nil, message=nil)+ |Asserts that the request was rendered with the appropriate template file.|
420
+
421
+ You'll see the usage of some of these assertions in the next chapter.
422
+
423
+ h3. Functional Tests for Your Controllers
424
+
425
+ 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.
426
+
427
+ h4. What to Include in your Functional Tests
428
+
429
+ You should test for things such as:
430
+
431
+ * was the web request successful?
432
+ * was the user redirected to the right page?
433
+ * was the user successfully authenticated?
434
+ * was the correct object stored in the response template?
435
+ * was the appropriate message displayed to the user in the view?
436
+
437
+ 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.
438
+
439
+ Let me take you through one such test, +test_should_get_index+ from the file +posts_controller_test.rb+.
440
+
441
+ <ruby>
442
+ test "should get index" do
443
+ get :index
444
+ assert_response :success
445
+ assert_not_nil assigns(:posts)
446
+ end
447
+ </ruby>
448
+
449
+ 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.
450
+
451
+ The +get+ method kicks off the web request and populates the results into the response. It accepts 4 arguments:
452
+
453
+ * The action of the controller you are requesting. This can be in the form of a string or a symbol.
454
+ * An optional hash of request parameters to pass into the action (eg. query string parameters or post variables).
455
+ * An optional hash of session variables to pass along with the request.
456
+ * An optional hash of flash values.
457
+
458
+ Example: Calling the +:show+ action, passing an +id+ of 12 as the +params+ and setting a +user_id+ of 5 in the session:
459
+
460
+ <ruby>
461
+ get(:show, {'id' => "12"}, {'user_id' => 5})
462
+ </ruby>
463
+
464
+ Another example: Calling the +:view+ action, passing an +id+ of 12 as the +params+, this time with no session, but with a flash message.
465
+
466
+ <ruby>
467
+ get(:view, {'id' => '12'}, nil, {'message' => 'booya!'})
468
+ </ruby>
469
+
470
+ 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.
471
+
472
+ Let us modify +test_should_create_post+ test in +posts_controller_test.rb+ so that all our test pass:
473
+
474
+ <ruby>
475
+ test "should create post" do
476
+ assert_difference('Post.count') do
477
+ post :create, :post => { :title => 'Some title'}
478
+ end
479
+
480
+ assert_redirected_to post_path(assigns(:post))
481
+ end
482
+ </ruby>
483
+
484
+ Now you can try running all the tests and they should pass.
485
+
486
+ h4. Available Request Types for Functional Tests
487
+
488
+ 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:
489
+
490
+ * +get+
491
+ * +post+
492
+ * +put+
493
+ * +head+
494
+ * +delete+
495
+
496
+ 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.
497
+
498
+ h4. The Four Hashes of the Apocalypse
499
+
500
+ 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:
501
+
502
+ * +assigns+ - Any objects that are stored as instance variables in actions for use in views.
503
+ * +cookies+ - Any cookies that are set.
504
+ * +flash+ - Any objects living in the flash.
505
+ * +session+ - Any object living in session variables.
506
+
507
+ 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:
508
+
509
+ <ruby>
510
+ flash["gordon"] flash[:gordon]
511
+ session["shmession"] session[:shmession]
512
+ cookies["are_good_for_u"] cookies[:are_good_for_u]
513
+
514
+ # Because you can't use assigns[:something] for historical reasons:
515
+ assigns["something"] assigns(:something)
516
+ </ruby>
517
+
518
+ h4. Instance Variables Available
519
+
520
+ You also have access to three instance variables in your functional tests:
521
+
522
+ * +@controller+ - The controller processing the request
523
+ * +@request+ - The request
524
+ * +@response+ - The response
525
+
526
+ h4. A Fuller Functional Test Example
527
+
528
+ Here's another example that uses +flash+, +assert_redirected_to+, and +assert_difference+:
529
+
530
+ <ruby>
531
+ test "should create post" do
532
+ assert_difference('Post.count') do
533
+ post :create, :post => { :title => 'Hi', :body => 'This is my first post.'}
534
+ end
535
+ assert_redirected_to post_path(assigns(:post))
536
+ assert_equal 'Post was successfully created.', flash[:notice]
537
+ end
538
+ </ruby>
539
+
540
+ h4. Testing Views
541
+
542
+ 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.
543
+
544
+ NOTE: You may find references to +assert_tag+ in other documentation, but this is now deprecated in favor of +assert_select+.
545
+
546
+ There are two forms of +assert_select+:
547
+
548
+ +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.
549
+
550
+ +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.
551
+
552
+ For example, you could verify the contents on the title element in your response with:
553
+
554
+ <ruby>
555
+ assert_select 'title', "Welcome to Rails Testing Guide"
556
+ </ruby>
557
+
558
+ 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:
559
+
560
+ <ruby>
561
+ assert_select 'ul.navigation' do
562
+ assert_select 'li.menu_item'
563
+ end
564
+ </ruby>
565
+
566
+ 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.
567
+
568
+ <ruby>
569
+ assert_select "ol" do |elements|
570
+ elements.each do |element|
571
+ assert_select element, "li", 4
572
+ end
573
+ end
574
+
575
+ assert_select "ol" do
576
+ assert_select "li", 8
577
+ end
578
+ </ruby>
579
+
580
+ The +assert_select+ assertion is quite powerful. For more advanced usage, refer to its "documentation":http://api.rubyonrails.org/classes/ActionController/Assertions/SelectorAssertions.html.
581
+
582
+ h5. Additional View-Based Assertions
583
+
584
+ There are more assertions that are primarily used in testing views:
585
+
586
+ |_.Assertion |_.Purpose|
587
+ |+assert_select_email+ |Allows you to make assertions on the body of an e-mail. |
588
+ |+assert_select_rjs+ |Allows you to make assertions on an 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.|
589
+ |+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.|
590
+ |+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.|
591
+
592
+ Here's an example of using +assert_select_email+:
593
+
594
+ <ruby>
595
+ assert_select_email do
596
+ assert_select 'small', 'Please click the "Unsubscribe" link if you want to opt-out.'
597
+ end
598
+ </ruby>
599
+
600
+ h3. Integration Testing
601
+
602
+ 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.
603
+
604
+ 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.
605
+
606
+ <shell>
607
+ $ script/generate integration_test user_flows
608
+ exists test/integration/
609
+ create test/integration/user_flows_test.rb
610
+ </shell>
611
+
612
+ Here's what a freshly-generated integration test looks like:
613
+
614
+ <ruby>
615
+ require 'test_helper'
616
+
617
+ class UserFlowsTest < ActionController::IntegrationTest
618
+ # fixtures :your, :models
619
+
620
+ # Replace this with your real tests.
621
+ test "the truth" do
622
+ assert true
623
+ end
624
+ end
625
+ </ruby>
626
+
627
+ 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.
628
+
629
+ h4. Helpers Available for Integration Tests
630
+
631
+ In addition to the standard testing helpers, there are some additional helpers available to integration tests:
632
+
633
+ |_.Helper |_.Purpose|
634
+ |+https?+ |Returns +true+ if the session is mimicking a secure HTTPS request.|
635
+ |+https!+ |Allows you to mimic a secure HTTPS request.|
636
+ |+host!+ |Allows you to set the host name to use in the next request.|
637
+ |+redirect?+ |Returns +true+ if the last request was a redirect.|
638
+ |+follow_redirect!+ |Follows a single redirect response.|
639
+ |+request_via_redirect(http_method, path, [parameters], [headers])+ |Allows you to make an HTTP request and follow any subsequent redirects.|
640
+ |+post_via_redirect(path, [parameters], [headers])+ |Allows you to make an HTTP POST request and follow any subsequent redirects.|
641
+ |+get_via_redirect(path, [parameters], [headers])+ |Allows you to make an HTTP GET request and follow any subsequent redirects.|
642
+ |+put_via_redirect(path, [parameters], [headers])+ |Allows you to make an HTTP PUT request and follow any subsequent redirects.|
643
+ |+delete_via_redirect(path, [parameters], [headers])+ |Allows you to make an HTTP DELETE request and follow any subsequent redirects.|
644
+ |+open_session+ |Opens a new session instance.|
645
+
646
+ h4. Integration Testing Examples
647
+
648
+ A simple integration test that exercises multiple controllers:
649
+
650
+ <ruby>
651
+ require 'test_helper'
652
+
653
+ class UserFlowsTest < ActionController::IntegrationTest
654
+ fixtures :users
655
+
656
+ test "login and browse site" do
657
+ # login via https
658
+ https!
659
+ get "/login"
660
+ assert_response :success
661
+
662
+ post_via_redirect "/login", :username => users(:avs).username, :password => users(:avs).password
663
+ assert_equal '/welcome', path
664
+ assert_equal 'Welcome avs!', flash[:notice]
665
+
666
+ https!(false)
667
+ get "/posts/all"
668
+ assert_response :success
669
+ assert assigns(:products)
670
+ end
671
+ end
672
+ </ruby>
673
+
674
+ 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.
675
+
676
+ Here's an example of multiple sessions and custom DSL in an integration test
677
+
678
+ <ruby>
679
+ require 'test_helper'
680
+
681
+ class UserFlowsTest < ActionController::IntegrationTest
682
+ fixtures :users
683
+
684
+ test "login and browse site" do
685
+
686
+ # User avs logs in
687
+ avs = login(:avs)
688
+ # User guest logs in
689
+ guest = login(:guest)
690
+
691
+ # Both are now available in different sessions
692
+ assert_equal 'Welcome avs!', avs.flash[:notice]
693
+ assert_equal 'Welcome guest!', guest.flash[:notice]
694
+
695
+ # User avs can browse site
696
+ avs.browses_site
697
+ # User guest can browse site as well
698
+ guest.browses_site
699
+
700
+ # Continue with other assertions
701
+ end
702
+
703
+ private
704
+
705
+ module CustomDsl
706
+ def browses_site
707
+ get "/products/all"
708
+ assert_response :success
709
+ assert assigns(:products)
710
+ end
711
+ end
712
+
713
+ def login(user)
714
+ open_session do |sess|
715
+ sess.extend(CustomDsl)
716
+ u = users(user)
717
+ sess.https!
718
+ sess.post "/login", :username => u.username, :password => u.password
719
+ assert_equal '/welcome', path
720
+ sess.https!(false)
721
+ end
722
+ end
723
+ end
724
+ </ruby>
725
+
726
+ h3. Rake Tasks for Running your Tests
727
+
728
+ You don't need to set up and run your tests by hand on a test-by-test basis. Rails comes with a number of rake tasks to help in testing. The table below lists all rake tasks that come along in the default Rakefile when you initiate a Rails project.
729
+
730
+ |_.Tasks |_.Description|
731
+ |+rake test+ |Runs all unit, functional and integration tests. You can also simply run +rake+ as the _test_ target is the default.|
732
+ |+rake test:units+ |Runs all the unit tests from +test/unit+|
733
+ |+rake test:functionals+ |Runs all the functional tests from +test/functional+|
734
+ |+rake test:integration+ |Runs all the integration tests from +test/integration+|
735
+ |+rake test:recent+ |Tests recent changes|
736
+ |+rake test:uncommitted+ |Runs all the tests which are uncommitted. Only supports Subversion|
737
+ |+rake test:plugins+ |Run all the plugin tests from +vendor/plugins/*/**/test+ (or specify with +PLUGIN=_name_+)|
738
+
739
+ h3. Brief Note About +Test::Unit+
740
+
741
+ 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.
742
+
743
+ NOTE: For more information on +Test::Unit+, refer to "test/unit Documentation":http://ruby-doc.org/stdlib/libdoc/test/unit/rdoc/
744
+
745
+ h3. Setup and Teardown
746
+
747
+ 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:
748
+
749
+ <ruby>
750
+ require 'test_helper'
751
+
752
+ class PostsControllerTest < ActionController::TestCase
753
+
754
+ # called before every single test
755
+ def setup
756
+ @post = posts(:one)
757
+ end
758
+
759
+ # called after every single test
760
+ def teardown
761
+ # as we are re-initializing @post before every test
762
+ # setting it to nil here is not essential but I hope
763
+ # you understand how you can use the teardown method
764
+ @post = nil
765
+ end
766
+
767
+ test "should show post" do
768
+ get :show, :id => @post.id
769
+ assert_response :success
770
+ end
771
+
772
+ test "should destroy post" do
773
+ assert_difference('Post.count', -1) do
774
+ delete :destroy, :id => @post.id
775
+ end
776
+
777
+ assert_redirected_to posts_path
778
+ end
779
+
780
+ end
781
+ </ruby>
782
+
783
+ 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:
784
+
785
+ * a block
786
+ * a method (like in the earlier example)
787
+ * a method name as a symbol
788
+ * a lambda
789
+
790
+ Let's see the earlier example by specifying +setup+ callback by specifying a method name as a symbol:
791
+
792
+ <ruby>
793
+ require '../test_helper'
794
+
795
+ class PostsControllerTest < ActionController::TestCase
796
+
797
+ # called before every single test
798
+ setup :initialize_post
799
+
800
+ # called after every single test
801
+ def teardown
802
+ @post = nil
803
+ end
804
+
805
+ test "should show post" do
806
+ get :show, :id => @post.id
807
+ assert_response :success
808
+ end
809
+
810
+ test "should update post" do
811
+ put :update, :id => @post.id, :post => { }
812
+ assert_redirected_to post_path(assigns(:post))
813
+ end
814
+
815
+ test "should destroy post" do
816
+ assert_difference('Post.count', -1) do
817
+ delete :destroy, :id => @post.id
818
+ end
819
+
820
+ assert_redirected_to posts_path
821
+ end
822
+
823
+ private
824
+
825
+ def initialize_post
826
+ @post = posts(:one)
827
+ end
828
+
829
+ end
830
+ </ruby>
831
+
832
+ h3. Testing Routes
833
+
834
+ 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:
835
+
836
+ <ruby>
837
+ test "should route to post" do
838
+ assert_routing '/posts/1', { :controller => "posts", :action => "show", :id => "1" }
839
+ end
840
+ </ruby>
841
+
842
+ h3. Testing Your Mailers
843
+
844
+ Testing mailer classes requires some specific tools to do a thorough job.
845
+
846
+ h4. Keeping the Postman in Check
847
+
848
+ Your +ActionMailer+ classes -- like every other part of your Rails application -- should be tested to ensure that it is working as expected.
849
+
850
+ The goals of testing your +ActionMailer+ classes are to ensure that:
851
+
852
+ * emails are being processed (created and sent)
853
+ * the email content is correct (subject, sender, body, etc)
854
+ * the right emails are being sent at the right times
855
+
856
+ h5. From All Sides
857
+
858
+ 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 -- 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.
859
+
860
+ h4. Unit Testing
861
+
862
+ 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.
863
+
864
+ h5. Revenge of the Fixtures
865
+
866
+ 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.
867
+
868
+ 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.
869
+
870
+ h5. The Basic Test Case
871
+
872
+ 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.
873
+
874
+ <ruby>
875
+ require 'test_helper'
876
+
877
+ class UserMailerTest < ActionMailer::TestCase
878
+ tests UserMailer
879
+ test "invite" do
880
+ @expected.from = 'me@example.com'
881
+ @expected.to = 'friend@example.com'
882
+ @expected.subject = "You have been invited by #{@expected.from}"
883
+ @expected.body = read_fixture('invite')
884
+ @expected.date = Time.now
885
+
886
+ assert_equal @expected.encoded, UserMailer.create_invite('me@example.com', 'friend@example.com', @expected.date).encoded
887
+ end
888
+
889
+ end
890
+ </ruby>
891
+
892
+ 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.
893
+
894
+ Here's the content of the +invite+ fixture:
895
+
896
+ <pre>
897
+ Hi friend@example.com,
898
+
899
+ You have been invited.
900
+
901
+ Cheers!
902
+ </pre>
903
+
904
+ 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+).
905
+
906
+ 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.
907
+
908
+ h4. Functional Testing
909
+
910
+ 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:
911
+
912
+ <ruby>
913
+ require 'test_helper'
914
+
915
+ class UserControllerTest < ActionController::TestCase
916
+ test "invite friend" do
917
+ assert_difference 'ActionMailer::Base.deliveries.size', +1 do
918
+ post :invite_friend, :email => 'friend@example.com'
919
+ end
920
+ invite_email = ActionMailer::Base.deliveries.first
921
+
922
+ assert_equal invite_email.subject, "You have been invited by me@example.com"
923
+ assert_equal invite_email.to[0], 'friend@example.com'
924
+ assert_match /Hi friend@example.com/, invite_email.body
925
+ end
926
+ end
927
+ </ruby>
928
+
929
+ h3. Other Testing Approaches
930
+
931
+ 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:
932
+
933
+ * "NullDB":http://avdi.org/projects/nulldb/, a way to speed up testing by avoiding database use.
934
+ * "Factory Girl":http://github.com/thoughtbot/factory_girl/tree/master, as replacement for fixtures.
935
+ * "Machinist":http://github.com/notahat/machinist/tree/master, another replacement for fixtures.
936
+ * "Shoulda":http://www.thoughtbot.com/projects/shoulda, an extension to +test/unit+ with additional helpers, macros, and assertions.
937
+ * "RSpec":http://rspec.info/, a behavior-driven development framework
938
+
939
+ h3. Changelog
940
+
941
+ "Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/8
942
+
943
+ * November 13, 2008: Revised based on feedback from Pratik Naik by "Akshay Surve":credits.html#asurve (not yet approved for publication)
944
+ * October 14, 2008: Edit and formatting pass by "Mike Gunderloy":credits.html#mgunderloy (not yet approved for publication)
945
+ * October 12, 2008: First draft by "Akshay Surve":credits.html#asurve (not yet approved for publication)
946
+