testing.textile 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947
  1. h2. A Guide to Testing Rails Applications
  2. This guide covers built-in mechanisms offered by Rails to test your application. By referring to this guide, you will be able to:
  3. * Understand Rails testing terminology
  4. * Write unit, functional and integration tests for your application
  5. * Identify other popular testing approaches and plugins
  6. This guide won't teach you to write a Rails application; it assumes basic familiarity with the Rails way of doing things.
  7. endprologue.
  8. h3. Why Write Tests for your Rails Applications?
  9. * Rails makes it super easy to write your tests. It starts by producing skeleton test code in the background while you are creating your models and controllers.
  10. * By simply running your Rails tests you can ensure your code adheres to the desired functionality even after some major code refactoring.
  11. * Rails tests can also simulate browser requests and thus you can test your application's response without having to test it through your browser.
  12. h3. Introduction to Testing
  13. 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.
  14. h4. The Three Environments
  15. Every Rails application you build has 3 sides: a side for production, a side for development, and a side for testing.
  16. 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:
  17. * production
  18. * development
  19. * test
  20. This allows you to set up and interact with test data without any danger of your tests altering data from your production environment.
  21. 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?
  22. 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+.
  23. h4. Rails Sets up for Testing from the Word Go
  24. Rails creates a +test+ folder for you as soon as you create a Rails project using +rails new+ _application_name_. If you list the contents of this folder then you shall see:
  25. <shell>
  26. $ ls -F test/
  27. fixtures/ functional/ integration/ test_helper.rb unit/
  28. </shell>
  29. 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.
  30. h4. The Low-Down on Fixtures
  31. 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.
  32. h5. What are Fixtures?
  33. _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 a single format: *YAML*.
  34. You'll find fixtures under your +test/fixtures+ directory. When you run +rails generate model+ to create a new model, fixture stubs will be automatically created and placed in this directory.
  35. h5. YAML
  36. 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+).
  37. Here's a sample YAML fixture file:
  38. <yaml>
  39. # lo & behold! I am a YAML comment!
  40. david:
  41. name: David Heinemeier Hansson
  42. birthday: 1979-10-15
  43. profession: Systems development
  44. steve:
  45. name: Steve Ross Kellock
  46. birthday: 1974-09-27
  47. profession: guy with keyboard
  48. </yaml>
  49. 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.
  50. h5. ERB'in It Up
  51. ERB allows you to embed ruby code within templates. YAML fixture format is pre-processed with ERB when you load fixtures. This allows you to use Ruby to help you generate some sample data.
  52. <erb>
  53. <% earth_size = 20 %>
  54. mercury:
  55. size: <%= earth_size / 50 %>
  56. brightest_on: <%= 113.days.ago.to_s(:db) %>
  57. venus:
  58. size: <%= earth_size / 2 %>
  59. brightest_on: <%= 67.days.ago.to_s(:db) %>
  60. mars:
  61. size: <%= earth_size - 69 %>
  62. brightest_on: <%= 13.days.from_now.to_s(:db) %>
  63. </erb>
  64. Anything encased within the
  65. <erb>
  66. <% %>
  67. </erb>
  68. 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.
  69. h5. Fixtures in Action
  70. Rails by default automatically loads all fixtures from the +test/fixtures+ folder for your unit and functional test. Loading involves three steps:
  71. * Remove any existing data from the table corresponding to the fixture
  72. * Load the fixture data into the table
  73. * Dump the fixture data into a variable in case you want to access it directly
  74. h5. Hashes with Special Powers
  75. 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:
  76. <ruby>
  77. # this will return the Hash for the fixture named david
  78. users(:david)
  79. # this will return the property for david called id
  80. users(:david).id
  81. </ruby>
  82. Fixtures can also transform themselves into the form of the original class. Thus, you can get at the methods only available to that class.
  83. <ruby>
  84. # using the find method, we grab the "real" david as a User
  85. david = users(:david).find
  86. # and now we have access to methods only available to a User class
  87. email(david.girlfriend.email, david.location_tonight)
  88. </ruby>
  89. h3. Unit Testing your Models
  90. In Rails, unit tests are what you write to test your models.
  91. For this guide we will be using Rails _scaffolding_. It will create the model, a migration, controller and views for the new resource in a single operation. It will also create a full test suite following Rails best practices. I will be using examples from this generated code and will be supplementing it with additional examples where necessary.
  92. NOTE: For more information on Rails <i>scaffolding</i>, refer to "Getting Started with Rails":getting_started.html
  93. When you use +rails generate scaffold+, for a resource among other things it creates a test stub in the +test/unit+ folder:
  94. <shell>
  95. $ rails generate scaffold post title:string body:text
  96. ...
  97. create app/models/post.rb
  98. create test/unit/post_test.rb
  99. create test/fixtures/posts.yml
  100. ...
  101. </shell>
  102. The default test stub in +test/unit/post_test.rb+ looks like this:
  103. <ruby>
  104. require 'test_helper'
  105. class PostTest < ActiveSupport::TestCase
  106. # Replace this with your real tests.
  107. test "the truth" do
  108. assert true
  109. end
  110. end
  111. </ruby>
  112. A line by line examination of this file will help get you oriented to Rails testing code and terminology.
  113. <ruby>
  114. require 'test_helper'
  115. </ruby>
  116. As you know by now, +test_helper.rb+ specifies the default configuration to run our tests. This is included with all the tests, so any methods added to this file are available to all your tests.
  117. <ruby>
  118. class PostTest < ActiveSupport::TestCase
  119. </ruby>
  120. 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.
  121. 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.
  122. Rails adds a +test+ method that takes a test name and a block. It generates a normal +Test::Unit+ test with method names prefixed with +test_+. So,
  123. <ruby>
  124. test "the truth" do
  125. assert true
  126. end
  127. </ruby>
  128. acts as if you had written
  129. <ruby>
  130. def test_the_truth
  131. assert true
  132. end
  133. </ruby>
  134. only the +test+ macro allows a more readable test name. You can still use regular method definitions though.
  135. NOTE: The method name is generated by replacing spaces with underscores. The result does not need to be a valid Ruby identifier though, the name may contain punctuation characters etc. That's because in Ruby technically any string may be a method name. Odd ones need +define_method+ and +send+ calls, but formally there's no restriction.
  136. <ruby>
  137. assert true
  138. </ruby>
  139. 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:
  140. * does this value = that value?
  141. * is this object nil?
  142. * does this line of code throw an exception?
  143. * is the user's password greater than 5 characters?
  144. Every test contains one or more assertions. Only when all the assertions are successful will the test pass.
  145. h4. Preparing your Application for Testing
  146. 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:
  147. <shell>
  148. $ rake db:migrate
  149. ...
  150. $ rake db:test:load
  151. </shell>
  152. The +rake db:migrate+ above runs any pending migrations on the _development_ environment and updates +db/schema.rb+. The +rake db:test:load+ recreates the test database from the current +db/schema.rb+. On subsequent attempts, it is a good idea to first run +db:test:prepare+, as it first checks for pending migrations and warns you appropriately.
  153. NOTE: +db:test:prepare+ will fail with an error if +db/schema.rb+ doesn't exist.
  154. h5. Rake Tasks for Preparing your Application for Testing
  155. |_.Tasks |_.Description|
  156. |+rake db:test:clone+ |Recreate the test database from the current environment's database schema|
  157. |+rake db:test:clone_structure+ |Recreate the test database from the development structure|
  158. |+rake db:test:load+ |Recreate the test database from the current +schema.rb+|
  159. |+rake db:test:prepare+ |Check for pending migrations and load the test schema|
  160. |+rake db:test:purge+ |Empty the test database.|
  161. TIP: You can see all these rake tasks and their descriptions by running +rake --tasks --describe+
  162. h4. Running Tests
  163. Running a test is as simple as invoking the file containing the test cases through Ruby:
  164. <shell>
  165. $ ruby -Itest test/unit/post_test.rb
  166. Loaded suite unit/post_test
  167. Started
  168. .
  169. Finished in 0.023513 seconds.
  170. 1 tests, 1 assertions, 0 failures, 0 errors
  171. </shell>
  172. This will run all the test methods from the test case. Note that +test_helper.rb+ is in the +test+ directory, hence this directory needs to be added to the load path using the +-I+ switch.
  173. You can also run a particular test method from the test case by using the +-n+ switch with the +test method name+.
  174. <shell>
  175. $ ruby -Itest test/unit/post_test.rb -n test_the_truth
  176. Loaded suite unit/post_test
  177. Started
  178. .
  179. Finished in 0.023513 seconds.
  180. 1 tests, 1 assertions, 0 failures, 0 errors
  181. </shell>
  182. 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.
  183. To see how a test failure is reported, you can add a failing test to the +post_test.rb+ test case.
  184. <ruby>
  185. test "should not save post without title" do
  186. post = Post.new
  187. assert !post.save
  188. end
  189. </ruby>
  190. Let us run this newly added test.
  191. <shell>
  192. $ ruby unit/post_test.rb -n test_should_not_save_post_without_title
  193. Loaded suite -e
  194. Started
  195. F
  196. Finished in 0.102072 seconds.
  197. 1) Failure:
  198. test_should_not_save_post_without_title(PostTest) [/test/unit/post_test.rb:6]:
  199. <false> is not true.
  200. 1 tests, 1 assertions, 1 failures, 0 errors
  201. </shell>
  202. 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:
  203. <ruby>
  204. test "should not save post without title" do
  205. post = Post.new
  206. assert !post.save, "Saved the post without a title"
  207. end
  208. </ruby>
  209. Running this test shows the friendlier assertion message:
  210. <shell>
  211. 1) Failure:
  212. test_should_not_save_post_without_title(PostTest) [/test/unit/post_test.rb:6]:
  213. Saved the post without a title.
  214. <false> is not true.
  215. </shell>
  216. Now to get this test to pass we can add a model level validation for the _title_ field.
  217. <ruby>
  218. class Post < ActiveRecord::Base
  219. validates :title, :presence => true
  220. end
  221. </ruby>
  222. Now the test should pass. Let us verify by running the test again:
  223. <shell>
  224. $ ruby unit/post_test.rb -n test_should_not_save_post_without_title
  225. Loaded suite unit/post_test
  226. Started
  227. .
  228. Finished in 0.193608 seconds.
  229. 1 tests, 1 assertions, 0 failures, 0 errors
  230. </shell>
  231. 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).
  232. 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.
  233. To see how an error gets reported, here's a test containing an error:
  234. <ruby>
  235. test "should report error" do
  236. # some_undefined_variable is not defined elsewhere in the test case
  237. some_undefined_variable
  238. assert true
  239. end
  240. </ruby>
  241. Now you can see even more output in the console from running the tests:
  242. <shell>
  243. $ ruby unit/post_test.rb -n test_should_report_error
  244. Loaded suite -e
  245. Started
  246. E
  247. Finished in 0.082603 seconds.
  248. 1) Error:
  249. test_should_report_error(PostTest):
  250. NameError: undefined local variable or method `some_undefined_variable' for #<PostTest:0x249d354>
  251. /test/unit/post_test.rb:6:in `test_should_report_error'
  252. 1 tests, 0 assertions, 0 failures, 1 errors
  253. </shell>
  254. Notice the 'E' in the output. It denotes a test with error.
  255. 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.
  256. h4. What to Include in Your Unit Tests
  257. 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.
  258. h4. Assertions Available
  259. 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.
  260. There are a bunch of different types of assertions you can use. Here's the complete list of assertions that ship with +test/unit+, the default testing library used by Rails. The +[msg]+ parameter is an optional string message you can specify to make your test failure messages clearer. It's not required.
  261. |_.Assertion |_.Purpose|
  262. |+assert( boolean, [msg] )+ |Ensures that the object/expression is true.|
  263. |+assert_equal( obj1, obj2, [msg] )+ |Ensures that +obj1 == obj2+ is true.|
  264. |+assert_not_equal( obj1, obj2, [msg] )+ |Ensures that +obj1 == obj2+ is false.|
  265. |+assert_same( obj1, obj2, [msg] )+ |Ensures that +obj1.equal?(obj2)+ is true.|
  266. |+assert_not_same( obj1, obj2, [msg] )+ |Ensures that +obj1.equal?(obj2)+ is false.|
  267. |+assert_nil( obj, [msg] )+ |Ensures that +obj.nil?+ is true.|
  268. |+assert_not_nil( obj, [msg] )+ |Ensures that +obj.nil?+ is false.|
  269. |+assert_match( regexp, string, [msg] )+ |Ensures that a string matches the regular expression.|
  270. |+assert_no_match( regexp, string, [msg] )+ |Ensures that a string doesn't match the regular expression.|
  271. |+assert_in_delta( expecting, actual, delta, [msg] )+ |Ensures that the numbers +expecting+ and +actual+ are within +delta+ of each other.|
  272. |+assert_throws( symbol, [msg] ) { block }+ |Ensures that the given block throws the symbol.|
  273. |+assert_raise( exception1, exception2, ... ) { block }+ |Ensures that the given block raises one of the given exceptions.|
  274. |+assert_nothing_raised( exception1, exception2, ... ) { block }+ |Ensures that the given block doesn't raise one of the given exceptions.|
  275. |+assert_instance_of( class, obj, [msg] )+ |Ensures that +obj+ is of the +class+ type.|
  276. |+assert_kind_of( class, obj, [msg] )+ |Ensures that +obj+ is or descends from +class+.|
  277. |+assert_respond_to( obj, symbol, [msg] )+ |Ensures that +obj+ has a method called +symbol+.|
  278. |+assert_operator( obj1, operator, obj2, [msg] )+ |Ensures that +obj1.operator(obj2)+ is true.|
  279. |+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?|
  280. |+flunk( [msg] )+ |Ensures failure. This is useful to explicitly mark a test that isn't finished yet.|
  281. 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.
  282. NOTE: Creating your own assertions is an advanced topic that we won't cover in this tutorial.
  283. h4. Rails Specific Assertions
  284. Rails adds some custom assertions of its own to the +test/unit+ framework:
  285. NOTE: +assert_valid(record)+ has been deprecated. Please use +assert(record.valid?)+ instead.
  286. |_.Assertion |_.Purpose|
  287. |+assert_valid(record)+ |Ensures that the passed record is valid by Active Record standards and returns any error messages if it is not.|
  288. |+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.|
  289. |+assert_no_difference(expressions, message = nil, &amp;block)+ |Asserts that the numeric result of evaluating an expression is not changed before and after invoking the passed in block.|
  290. |+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.|
  291. |+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.|
  292. |+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|
  293. |+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.|
  294. |+assert_template(expected = nil, message=nil)+ |Asserts that the request was rendered with the appropriate template file.|
  295. You'll see the usage of some of these assertions in the next chapter.
  296. h3. Functional Tests for Your Controllers
  297. 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.
  298. h4. What to Include in your Functional Tests
  299. You should test for things such as:
  300. * was the web request successful?
  301. * was the user redirected to the right page?
  302. * was the user successfully authenticated?
  303. * was the correct object stored in the response template?
  304. * was the appropriate message displayed to the user in the view?
  305. 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.
  306. Let me take you through one such test, +test_should_get_index+ from the file +posts_controller_test.rb+.
  307. <ruby>
  308. test "should get index" do
  309. get :index
  310. assert_response :success
  311. assert_not_nil assigns(:posts)
  312. end
  313. </ruby>
  314. 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.
  315. The +get+ method kicks off the web request and populates the results into the response. It accepts 4 arguments:
  316. * The action of the controller you are requesting. This can be in the form of a string or a symbol.
  317. * An optional hash of request parameters to pass into the action (eg. query string parameters or post variables).
  318. * An optional hash of session variables to pass along with the request.
  319. * An optional hash of flash values.
  320. Example: Calling the +:show+ action, passing an +id+ of 12 as the +params+ and setting a +user_id+ of 5 in the session:
  321. <ruby>
  322. get(:show, {'id' => "12"}, {'user_id' => 5})
  323. </ruby>
  324. Another example: Calling the +:view+ action, passing an +id+ of 12 as the +params+, this time with no session, but with a flash message.
  325. <ruby>
  326. get(:view, {'id' => '12'}, nil, {'message' => 'booya!'})
  327. </ruby>
  328. 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.
  329. Let us modify +test_should_create_post+ test in +posts_controller_test.rb+ so that all our test pass:
  330. <ruby>
  331. test "should create post" do
  332. assert_difference('Post.count') do
  333. post :create, :post => { :title => 'Some title'}
  334. end
  335. assert_redirected_to post_path(assigns(:post))
  336. end
  337. </ruby>
  338. Now you can try running all the tests and they should pass.
  339. h4. Available Request Types for Functional Tests
  340. 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:
  341. * +get+
  342. * +post+
  343. * +put+
  344. * +head+
  345. * +delete+
  346. 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.
  347. NOTE: Functional tests do not verify whether the specified request type should be accepted by the action. Request types in this context exist to make your tests more descriptive.
  348. h4. The Four Hashes of the Apocalypse
  349. 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:
  350. * +assigns+ - Any objects that are stored as instance variables in actions for use in views.
  351. * +cookies+ - Any cookies that are set.
  352. * +flash+ - Any objects living in the flash.
  353. * +session+ - Any object living in session variables.
  354. 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:
  355. <ruby>
  356. flash["gordon"] flash[:gordon]
  357. session["shmession"] session[:shmession]
  358. cookies["are_good_for_u"] cookies[:are_good_for_u]
  359. # Because you can't use assigns[:something] for historical reasons:
  360. assigns["something"] assigns(:something)
  361. </ruby>
  362. h4. Instance Variables Available
  363. You also have access to three instance variables in your functional tests:
  364. * +@controller+ - The controller processing the request
  365. * +@request+ - The request
  366. * +@response+ - The response
  367. h4. A Fuller Functional Test Example
  368. Here's another example that uses +flash+, +assert_redirected_to+, and +assert_difference+:
  369. <ruby>
  370. test "should create post" do
  371. assert_difference('Post.count') do
  372. post :create, :post => { :title => 'Hi', :body => 'This is my first post.'}
  373. end
  374. assert_redirected_to post_path(assigns(:post))
  375. assert_equal 'Post was successfully created.', flash[:notice]
  376. end
  377. </ruby>
  378. h4. Testing Views
  379. 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.
  380. NOTE: You may find references to +assert_tag+ in other documentation, but this is now deprecated in favor of +assert_select+.
  381. There are two forms of +assert_select+:
  382. +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.
  383. +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.
  384. For example, you could verify the contents on the title element in your response with:
  385. <ruby>
  386. assert_select 'title', "Welcome to Rails Testing Guide"
  387. </ruby>
  388. 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:
  389. <ruby>
  390. assert_select 'ul.navigation' do
  391. assert_select 'li.menu_item'
  392. end
  393. </ruby>
  394. 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.
  395. <ruby>
  396. assert_select "ol" do |elements|
  397. elements.each do |element|
  398. assert_select element, "li", 4
  399. end
  400. end
  401. assert_select "ol" do
  402. assert_select "li", 8
  403. end
  404. </ruby>
  405. The +assert_select+ assertion is quite powerful. For more advanced usage, refer to its "documentation":http://api.rubyonrails.org/classes/ActionDispatch/Assertions/SelectorAssertions.html.
  406. h5. Additional View-Based Assertions
  407. There are more assertions that are primarily used in testing views:
  408. |_.Assertion |_.Purpose|
  409. |+assert_select_email+ |Allows you to make assertions on the body of an e-mail. |
  410. |+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.|
  411. |+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.|
  412. Here's an example of using +assert_select_email+:
  413. <ruby>
  414. assert_select_email do
  415. assert_select 'small', 'Please click the "Unsubscribe" link if you want to opt-out.'
  416. end
  417. </ruby>
  418. h3. Integration Testing
  419. 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.
  420. 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.
  421. <shell>
  422. $ rails generate integration_test user_flows
  423. exists test/integration/
  424. create test/integration/user_flows_test.rb
  425. </shell>
  426. Here's what a freshly-generated integration test looks like:
  427. <ruby>
  428. require 'test_helper'
  429. class UserFlowsTest < ActionDispatch::IntegrationTest
  430. fixtures :all
  431. # Replace this with your real tests.
  432. test "the truth" do
  433. assert true
  434. end
  435. end
  436. </ruby>
  437. Integration tests inherit from +ActionDispatch::IntegrationTest+. This makes available some additional helpers to use in your integration tests. Also you need to explicitly include the fixtures to be made available to the test.
  438. h4. Helpers Available for Integration Tests
  439. In addition to the standard testing helpers, there are some additional helpers available to integration tests:
  440. |_.Helper |_.Purpose|
  441. |+https?+ |Returns +true+ if the session is mimicking a secure HTTPS request.|
  442. |+https!+ |Allows you to mimic a secure HTTPS request.|
  443. |+host!+ |Allows you to set the host name to use in the next request.|
  444. |+redirect?+ |Returns +true+ if the last request was a redirect.|
  445. |+follow_redirect!+ |Follows a single redirect response.|
  446. |+request_via_redirect(http_method, path, [parameters], [headers])+ |Allows you to make an HTTP request and follow any subsequent redirects.|
  447. |+post_via_redirect(path, [parameters], [headers])+ |Allows you to make an HTTP POST request and follow any subsequent redirects.|
  448. |+get_via_redirect(path, [parameters], [headers])+ |Allows you to make an HTTP GET request and follow any subsequent redirects.|
  449. |+put_via_redirect(path, [parameters], [headers])+ |Allows you to make an HTTP PUT request and follow any subsequent redirects.|
  450. |+delete_via_redirect(path, [parameters], [headers])+ |Allows you to make an HTTP DELETE request and follow any subsequent redirects.|
  451. |+open_session+ |Opens a new session instance.|
  452. h4. Integration Testing Examples
  453. A simple integration test that exercises multiple controllers:
  454. <ruby>
  455. require 'test_helper'
  456. class UserFlowsTest < ActionDispatch::IntegrationTest
  457. fixtures :users
  458. test "login and browse site" do
  459. # login via https
  460. https!
  461. get "/login"
  462. assert_response :success
  463. post_via_redirect "/login", :username => users(:avs).username, :password => users(:avs).password
  464. assert_equal '/welcome', path
  465. assert_equal 'Welcome avs!', flash[:notice]
  466. https!(false)
  467. get "/posts/all"
  468. assert_response :success
  469. assert assigns(:products)
  470. end
  471. end
  472. </ruby>
  473. 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.
  474. Here's an example of multiple sessions and custom DSL in an integration test
  475. <ruby>
  476. require 'test_helper'
  477. class UserFlowsTest < ActionDispatch::IntegrationTest
  478. fixtures :users
  479. test "login and browse site" do
  480. # User avs logs in
  481. avs = login(:avs)
  482. # User guest logs in
  483. guest = login(:guest)
  484. # Both are now available in different sessions
  485. assert_equal 'Welcome avs!', avs.flash[:notice]
  486. assert_equal 'Welcome guest!', guest.flash[:notice]
  487. # User avs can browse site
  488. avs.browses_site
  489. # User guest can browse site as well
  490. guest.browses_site
  491. # Continue with other assertions
  492. end
  493. private
  494. module CustomDsl
  495. def browses_site
  496. get "/products/all"
  497. assert_response :success
  498. assert assigns(:products)
  499. end
  500. end
  501. def login(user)
  502. open_session do |sess|
  503. sess.extend(CustomDsl)
  504. u = users(user)
  505. sess.https!
  506. sess.post "/login", :username => u.username, :password => u.password
  507. assert_equal '/welcome', path
  508. sess.https!(false)
  509. end
  510. end
  511. end
  512. </ruby>
  513. h3. Rake Tasks for Running your Tests
  514. 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.
  515. |_.Tasks |_.Description|
  516. |+rake test+ |Runs all unit, functional and integration tests. You can also simply run +rake+ as the _test_ target is the default.|
  517. |+rake test:benchmark+ |Benchmark the performance tests|
  518. |+rake test:functionals+ |Runs all the functional tests from +test/functional+|
  519. |+rake test:integration+ |Runs all the integration tests from +test/integration+|
  520. |+rake test:plugins+ |Run all the plugin tests from +vendor/plugins/*/**/test+ (or specify with +PLUGIN=_name_+)|
  521. |+rake test:profile+ |Profile the performance tests|
  522. |+rake test:recent+ |Tests recent changes|
  523. |+rake test:uncommitted+ |Runs all the tests which are uncommitted. Supports Subversion and Git|
  524. |+rake test:units+ |Runs all the unit tests from +test/unit+|
  525. h3. Brief Note About +Test::Unit+
  526. 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+, allowing
  527. us to use all of the basic assertions in our tests.
  528. NOTE: For more information on +Test::Unit+, refer to "test/unit Documentation":http://ruby-doc.org/stdlib/libdoc/test/unit/rdoc/
  529. h3. Setup and Teardown
  530. 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:
  531. <ruby>
  532. require 'test_helper'
  533. class PostsControllerTest < ActionController::TestCase
  534. # called before every single test
  535. def setup
  536. @post = posts(:one)
  537. end
  538. # called after every single test
  539. def teardown
  540. # as we are re-initializing @post before every test
  541. # setting it to nil here is not essential but I hope
  542. # you understand how you can use the teardown method
  543. @post = nil
  544. end
  545. test "should show post" do
  546. get :show, :id => @post.id
  547. assert_response :success
  548. end
  549. test "should destroy post" do
  550. assert_difference('Post.count', -1) do
  551. delete :destroy, :id => @post.id
  552. end
  553. assert_redirected_to posts_path
  554. end
  555. end
  556. </ruby>
  557. 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:
  558. * a block
  559. * a method (like in the earlier example)
  560. * a method name as a symbol
  561. * a lambda
  562. Let's see the earlier example by specifying +setup+ callback by specifying a method name as a symbol:
  563. <ruby>
  564. require '../test_helper'
  565. class PostsControllerTest < ActionController::TestCase
  566. # called before every single test
  567. setup :initialize_post
  568. # called after every single test
  569. def teardown
  570. @post = nil
  571. end
  572. test "should show post" do
  573. get :show, :id => @post.id
  574. assert_response :success
  575. end
  576. test "should update post" do
  577. put :update, :id => @post.id, :post => { }
  578. assert_redirected_to post_path(assigns(:post))
  579. end
  580. test "should destroy post" do
  581. assert_difference('Post.count', -1) do
  582. delete :destroy, :id => @post.id
  583. end
  584. assert_redirected_to posts_path
  585. end
  586. private
  587. def initialize_post
  588. @post = posts(:one)
  589. end
  590. end
  591. </ruby>
  592. h3. Testing Routes
  593. 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:
  594. <ruby>
  595. test "should route to post" do
  596. assert_routing '/posts/1', { :controller => "posts", :action => "show", :id => "1" }
  597. end
  598. </ruby>
  599. h3. Testing Your Mailers
  600. Testing mailer classes requires some specific tools to do a thorough job.
  601. h4. Keeping the Postman in Check
  602. Your mailer classes -- like every other part of your Rails application -- should be tested to ensure that it is working as expected.
  603. The goals of testing your mailer classes are to ensure that:
  604. * emails are being processed (created and sent)
  605. * the email content is correct (subject, sender, body, etc)
  606. * the right emails are being sent at the right times
  607. h5. From All Sides
  608. There are two aspects of testing your mailer, the unit tests and the functional tests. In the unit tests, you run the mailer in isolation with tightly controlled inputs and compare the output to a known value (a fixture.) In the functional tests you don't so much test the minute details produced by the mailer; instead, we test that our controllers and models are using the mailer in the right way. You test to prove that the right email was sent at the right time.
  609. h4. Unit Testing
  610. 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.
  611. h5. Revenge of the Fixtures
  612. 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.
  613. 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.
  614. h5. The Basic Test Case
  615. 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.
  616. <ruby>
  617. require 'test_helper'
  618. class UserMailerTest < ActionMailer::TestCase
  619. tests UserMailer
  620. test "invite" do
  621. @expected.from = 'me@example.com'
  622. @expected.to = 'friend@example.com'
  623. @expected.subject = "You have been invited by #{@expected.from}"
  624. @expected.body = read_fixture('invite')
  625. @expected.date = Time.now
  626. assert_equal @expected.encoded, UserMailer.create_invite('me@example.com', 'friend@example.com', @expected.date).encoded
  627. end
  628. end
  629. </ruby>
  630. 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.
  631. Here's the content of the +invite+ fixture:
  632. <pre>
  633. Hi friend@example.com,
  634. You have been invited.
  635. Cheers!
  636. </pre>
  637. 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+).
  638. 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.
  639. h4. Functional Testing
  640. Functional testing for mailers involves more than just checking that the email body, recipients and so forth are correct. In functional mail tests you call the mail deliver methods and check that the appropriate emails have been appended to the delivery list. It is fairly safe to assume that the deliver methods themselves do their job. You are probably more interested in whether your own business logic is sending emails when you expect them to go out. For example, you can check that the invite friend operation is sending an email appropriately:
  641. <ruby>
  642. require 'test_helper'
  643. class UserControllerTest < ActionController::TestCase
  644. test "invite friend" do
  645. assert_difference 'ActionMailer::Base.deliveries.size', +1 do
  646. post :invite_friend, :email => 'friend@example.com'
  647. end
  648. invite_email = ActionMailer::Base.deliveries.last
  649. assert_equal "You have been invited by me@example.com", invite_email.subject
  650. assert_equal 'friend@example.com', invite_email.to[0]
  651. assert_match(/Hi friend@example.com/, invite_email.body)
  652. end
  653. end
  654. </ruby>
  655. h3. Other Testing Approaches
  656. 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:
  657. * "NullDB":http://avdi.org/projects/nulldb/, a way to speed up testing by avoiding database use.
  658. * "Factory Girl":https://github.com/thoughtbot/factory_girl/tree/master, a replacement for fixtures.
  659. * "Machinist":https://github.com/notahat/machinist/tree/master, another replacement for fixtures.
  660. * "Shoulda":http://www.thoughtbot.com/projects/shoulda, an extension to +test/unit+ with additional helpers, macros, and assertions.
  661. * "RSpec":http://relishapp.com/rspec, a behavior-driven development framework