aboutsummaryrefslogtreecommitdiffstats
path: root/guides/source/testing.md
diff options
context:
space:
mode:
authorPrem Sichanugrist <s@sikachu.com>2012-09-01 21:37:59 -0400
committerPrem Sichanugrist <s@sikac.hu>2012-09-17 15:54:23 -0400
commit31ef4cf656785a190723d2d8fb4c0fd06f4009bc (patch)
tree582a93b9441b41c1150ae421a2a878194af6475e /guides/source/testing.md
parented62b1bf0b6fff53524c168f9615af84dea99537 (diff)
downloadrails-31ef4cf656785a190723d2d8fb4c0fd06f4009bc.tar.gz
rails-31ef4cf656785a190723d2d8fb4c0fd06f4009bc.tar.bz2
rails-31ef4cf656785a190723d2d8fb4c0fd06f4009bc.zip
Convert all inline codes to Markdown syntax
Diffstat (limited to 'guides/source/testing.md')
-rw-r--r--guides/source/testing.md270
1 files changed, 135 insertions, 135 deletions
diff --git a/guides/source/testing.md b/guides/source/testing.md
index 878e2eeb87..59213ec43f 100644
--- a/guides/source/testing.md
+++ b/guides/source/testing.md
@@ -26,13 +26,13 @@ Testing support was woven into the Rails fabric from the beginning. It wasn't an
### The Test Environment
-By default, every Rails application has three environments: development, test, and production. The database for each one of them is configured in +config/database.yml+.
+By default, every Rails application has three environments: development, test, and production. The database for each one of them is configured in `config/database.yml`.
A dedicated test database allows you to set up and interact with test data in isolation. Tests can mangle test data with confidence, that won't touch the data in the development or production databases.
### Rails Sets up for Testing from the Word Go
-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:
+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:
```bash
$ ls -F test
@@ -40,11 +40,11 @@ $ ls -F test
fixtures/ functional/ integration/ performance/ test_helper.rb unit/
```
-The +unit+ directory is meant to hold tests for your models, the +functional+ directory is meant to hold tests for your controllers, the +integration+ directory is meant to hold tests that involve any number of controllers interacting, and the +performance+ directory is meant for performance tests.
+The `unit` directory is meant to hold tests for your models, the `functional` directory is meant to hold tests for your controllers, the `integration` directory is meant to hold tests that involve any number of controllers interacting, and the `performance` directory is meant for performance tests.
-Fixtures are a way of organizing test data; they reside in the +fixtures+ folder.
+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.
+The `test_helper.rb` file holds the default configuration for your tests.
### The Low-Down on Fixtures
@@ -54,11 +54,11 @@ For good tests, you'll need to give some thought to setting up test data. In Rai
_Fixtures_ is a fancy word for sample data. Fixtures allow you to populate your testing database with predefined data before your tests run. Fixtures are database independent written in YAML. There is one file per model.
-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.
+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.
#### YAML
-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+).
+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`).
Here's a sample YAML fixture file:
@@ -91,7 +91,7 @@ user_<%= n %>:
#### Fixtures in Action
-Rails by default automatically loads all fixtures from the +test/fixtures+ folder for your unit and functional test. Loading involves three steps:
+Rails by default automatically loads all fixtures from the `test/fixtures` folder for your unit and functional test. Loading involves three steps:
* Remove any existing data from the table corresponding to the fixture
* Load the fixture data into the table
@@ -121,7 +121,7 @@ For this guide we will be using Rails _scaffolding_. It will create the model, a
NOTE: For more information on Rails <i>scaffolding</i>, refer to "Getting Started with Rails":getting_started.html
-When you use +rails generate scaffold+, for a resource among other things it creates a test stub in the +test/unit+ folder:
+When you use `rails generate scaffold`, for a resource among other things it creates a test stub in the `test/unit` folder:
```bash
$ rails generate scaffold post title:string body:text
@@ -132,7 +132,7 @@ create test/fixtures/posts.yml
...
```
-The default test stub in +test/unit/post_test.rb+ looks like this:
+The default test stub in `test/unit/post_test.rb` looks like this:
```ruby
require 'test_helper'
@@ -151,17 +151,17 @@ A line by line examination of this file will help get you oriented to Rails test
require 'test_helper'
```
-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.
+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.
```ruby
class PostTest < ActiveSupport::TestCase
```
-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.
+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.
-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.
+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.
-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,
+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,
```ruby
test "the truth" do
@@ -177,9 +177,9 @@ def test_the_truth
end
```
-only the +test+ macro allows a more readable test name. You can still use regular method definitions though.
+only the `test` macro allows a more readable test name. You can still use regular method definitions though.
-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.
+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.
```ruby
assert true
@@ -204,20 +204,20 @@ $ rake db:migrate
$ rake db:test:load
```
-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.
+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.
-NOTE: +db:test:prepare+ will fail with an error if +db/schema.rb+ doesn't exist.
+NOTE: `db:test:prepare` will fail with an error if `db/schema.rb` doesn't exist.
#### Rake Tasks for Preparing your Application for Testing
|_.Tasks |_.Description|
-|+rake db:test:clone+ |Recreate the test database from the current environment's database schema|
-|+rake db:test:clone_structure+ |Recreate the test database from the development structure|
-|+rake db:test:load+ |Recreate the test database from the current +schema.rb+|
-|+rake db:test:prepare+ |Check for pending migrations and load the test schema|
-|+rake db:test:purge+ |Empty the test database.|
+|`rake db:test:clone` |Recreate the test database from the current environment's database schema|
+|`rake db:test:clone_structure` |Recreate the test database from the development structure|
+|`rake db:test:load` |Recreate the test database from the current `schema.rb`|
+|`rake db:test:prepare` |Check for pending migrations and load the test schema|
+|`rake db:test:purge` |Empty the test database.|
-TIP: You can see all these rake tasks and their descriptions by running +rake --tasks --describe+
+TIP: You can see all these rake tasks and their descriptions by running `rake --tasks --describe`
### Running Tests
@@ -234,9 +234,9 @@ Finished in 0.023513 seconds.
1 tests, 1 assertions, 0 failures, 0 errors
```
-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.
+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.
-You can also run a particular test method from the test case by using the +-n+ switch with the +test method name+.
+You can also run a particular test method from the test case by using the `-n` switch with the `test method name`.
```bash
$ ruby -Itest test/unit/post_test.rb -n test_the_truth
@@ -249,9 +249,9 @@ Finished in 0.023513 seconds.
1 tests, 1 assertions, 0 failures, 0 errors
```
-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.
+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.
-To see how a test failure is reported, you can add a failing test to the +post_test.rb+ test case.
+To see how a test failure is reported, you can add a failing test to the `post_test.rb` test case.
```ruby
test "should not save post without title" do
@@ -276,7 +276,7 @@ test_should_not_save_post_without_title(PostTest) [/test/unit/post_test.rb:6]:
1 tests, 1 assertions, 1 failures, 0 errors
```
-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:
+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:
```ruby
test "should not save post without title" do
@@ -357,28 +357,28 @@ Ideally, you would like to include a test for everything which could possibly br
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.
-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.
+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.
|_.Assertion |_.Purpose|
-|+assert( boolean, [msg] )+ |Ensures that the object/expression is true.|
-|+assert_equal( expected, actual, [msg] )+ |Ensures that +expected == actual+ is true.|
-|+assert_not_equal( expected, actual, [msg] )+ |Ensures that +expected != actual+ is true.|
-|+assert_same( expected, actual, [msg] )+ |Ensures that +expected.equal?(actual)+ is true.|
-|+assert_not_same( expected, actual, [msg] )+ |Ensures that +!expected.equal?(actual)+ is true.|
-|+assert_nil( obj, [msg] )+ |Ensures that +obj.nil?+ is true.|
-|+assert_not_nil( obj, [msg] )+ |Ensures that +!obj.nil?+ is true.|
-|+assert_match( regexp, string, [msg] )+ |Ensures that a string matches the regular expression.|
-|+assert_no_match( regexp, string, [msg] )+ |Ensures that a string doesn't match the regular expression.|
-|+assert_in_delta( expecting, actual, delta, [msg] )+ |Ensures that the numbers +expecting+ and +actual+ are within +delta+ of each other.|
-|+assert_throws( symbol, [msg] ) { block }+ |Ensures that the given block throws the symbol.|
-|+assert_raise( exception1, exception2, ... ) { block }+ |Ensures that the given block raises one of the given exceptions.|
-|+assert_nothing_raised( exception1, exception2, ... ) { block }+ |Ensures that the given block doesn't raise one of the given exceptions.|
-|+assert_instance_of( class, obj, [msg] )+ |Ensures that +obj+ is of the +class+ type.|
-|+assert_kind_of( class, obj, [msg] )+ |Ensures that +obj+ is or descends from +class+.|
-|+assert_respond_to( obj, symbol, [msg] )+ |Ensures that +obj+ has a method called +symbol+.|
-|+assert_operator( obj1, operator, obj2, [msg] )+ |Ensures that +obj1.operator(obj2)+ is true.|
-|+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?|
-|+flunk( [msg] )+ |Ensures failure. This is useful to explicitly mark a test that isn't finished yet.|
+|`assert( boolean, [msg] )` |Ensures that the object/expression is true.|
+|`assert_equal( expected, actual, [msg] )` |Ensures that `expected == actual` is true.|
+|`assert_not_equal( expected, actual, [msg] )` |Ensures that `expected != actual` is true.|
+|`assert_same( expected, actual, [msg] )` |Ensures that `expected.equal?(actual)` is true.|
+|`assert_not_same( expected, actual, [msg] )` |Ensures that `!expected.equal?(actual)` is true.|
+|`assert_nil( obj, [msg] )` |Ensures that `obj.nil?` is true.|
+|`assert_not_nil( obj, [msg] )` |Ensures that `!obj.nil?` is true.|
+|`assert_match( regexp, string, [msg] )` |Ensures that a string matches the regular expression.|
+|`assert_no_match( regexp, string, [msg] )` |Ensures that a string doesn't match the regular expression.|
+|`assert_in_delta( expecting, actual, delta, [msg] )` |Ensures that the numbers `expecting` and `actual` are within `delta` of each other.|
+|`assert_throws( symbol, [msg] ) { block }` |Ensures that the given block throws the symbol.|
+|`assert_raise( exception1, exception2, ... ) { block }` |Ensures that the given block raises one of the given exceptions.|
+|`assert_nothing_raised( exception1, exception2, ... ) { block }` |Ensures that the given block doesn't raise one of the given exceptions.|
+|`assert_instance_of( class, obj, [msg] )` |Ensures that `obj` is of the `class` type.|
+|`assert_kind_of( class, obj, [msg] )` |Ensures that `obj` is or descends from `class`.|
+|`assert_respond_to( obj, symbol, [msg] )` |Ensures that `obj` has a method called `symbol`.|
+|`assert_operator( obj1, operator, obj2, [msg] )` |Ensures that `obj1.operator(obj2)` is true.|
+|`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?|
+|`flunk( [msg] )` |Ensures failure. This is useful to explicitly mark a test that isn't finished yet.|
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.
@@ -386,19 +386,19 @@ NOTE: Creating your own assertions is an advanced topic that we won't cover in t
### Rails Specific Assertions
-Rails adds some custom assertions of its own to the +test/unit+ framework:
+Rails adds some custom assertions of its own to the `test/unit` framework:
-NOTE: +assert_valid(record)+ has been deprecated. Please use +assert(record.valid?)+ instead.
+NOTE: `assert_valid(record)` has been deprecated. Please use `assert(record.valid?)` instead.
|_.Assertion |_.Purpose|
-|+assert_valid(record)+ |Ensures that the passed record is valid by Active Record standards and returns any error messages if it is not.|
-|+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.|
-|+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.|
-|+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.|
-|+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.|
-|+assert_response(type, message = nil)+ |Asserts that the response comes with a specific status code. You can specify +:success+ to indicate 200-299, +:redirect+ to indicate 300-399, +:missing+ to indicate 404, or +:error+ to match the 500-599 range|
-|+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.|
-|+assert_template(expected = nil, message=nil)+ |Asserts that the request was rendered with the appropriate template file.|
+|`assert_valid(record)` |Ensures that the passed record is valid by Active Record standards and returns any error messages if it is not.|
+|`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.|
+|`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.|
+|`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.|
+|`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.|
+|`assert_response(type, message = nil)` |Asserts that the response comes with a specific status code. You can specify `:success` to indicate 200-299, `:redirect` to indicate 300-399, `:missing` to indicate 404, or `:error` to match the 500-599 range|
+|`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.|
+|`assert_template(expected = nil, message=nil)` |Asserts that the request was rendered with the appropriate template file.|
You'll see the usage of some of these assertions in the next chapter.
@@ -417,9 +417,9 @@ You should test for things such as:
* was the correct object stored in the response template?
* was the appropriate message displayed to the user in the view?
-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.
+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.
-Let me take you through one such test, +test_should_get_index+ from the file +posts_controller_test.rb+.
+Let me take you through one such test, `test_should_get_index` from the file `posts_controller_test.rb`.
```ruby
test "should get index" do
@@ -429,30 +429,30 @@ test "should get index" do
end
```
-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.
+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.
-The +get+ method kicks off the web request and populates the results into the response. It accepts 4 arguments:
+The `get` method kicks off the web request and populates the results into the response. It accepts 4 arguments:
* The action of the controller you are requesting. This can be in the form of a string or a symbol.
* An optional hash of request parameters to pass into the action (eg. query string parameters or post variables).
* An optional hash of session variables to pass along with the request.
* An optional hash of flash values.
-Example: Calling the +:show+ action, passing an +id+ of 12 as the +params+ and setting a +user_id+ of 5 in the session:
+Example: Calling the `:show` action, passing an `id` of 12 as the `params` and setting a `user_id` of 5 in the session:
```ruby
get(:show, {'id' => "12"}, {'user_id' => 5})
```
-Another example: Calling the +:view+ action, passing an +id+ of 12 as the +params+, this time with no session, but with a flash message.
+Another example: Calling the `:view` action, passing an `id` of 12 as the `params`, this time with no session, but with a flash message.
```ruby
get(:view, {'id' => '12'}, nil, {'message' => 'booya!'})
```
-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.
+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.
-Let us modify +test_should_create_post+ test in +posts_controller_test.rb+ so that all our test pass:
+Let us modify `test_should_create_post` test in `posts_controller_test.rb` so that all our test pass:
```ruby
test "should create post" do
@@ -468,14 +468,14 @@ Now you can try running all the tests and they should pass.
### Available Request Types for Functional Tests
-If you're familiar with the HTTP protocol, you'll know that +get+ is a type of request. There are 6 request types supported in Rails functional tests:
+If you're familiar with the HTTP protocol, you'll know that `get` is a type of request. There are 6 request types supported in Rails functional tests:
-* +get+
-* +post+
-* +patch+
-* +put+
-* +head+
-* +delete+
+* `get`
+* `post`
+* `patch`
+* `put`
+* `head`
+* `delete`
All of request types are methods that you can use, however, you'll probably end up using the first two more often than the others.
@@ -483,14 +483,14 @@ NOTE: Functional tests do not verify whether the specified request type should b
### The Four Hashes of the Apocalypse
-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:
+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:
-* +assigns+ - Any objects that are stored as instance variables in actions for use in views.
-* +cookies+ - Any cookies that are set.
-* +flash+ - Any objects living in the flash.
-* +session+ - Any object living in session variables.
+* `assigns` - Any objects that are stored as instance variables in actions for use in views.
+* `cookies` - Any cookies that are set.
+* `flash` - Any objects living in the flash.
+* `session` - Any object living in session variables.
-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:
+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:
```ruby
flash["gordon"] flash[:gordon]
@@ -505,13 +505,13 @@ assigns["something"] assigns(:something)
You also have access to three instance variables in your functional tests:
-* +@controller+ - The controller processing the request
-* +@request+ - The request
-* +@response+ - The response
+* `@controller` - The controller processing the request
+* `@request` - The request
+* `@response` - The response
### Testing Templates and Layouts
-If you want to make sure that the response rendered the correct template and layout, you can use the +assert_template+
+If you want to make sure that the response rendered the correct template and layout, you can use the `assert_template`
method:
```ruby
@@ -522,8 +522,8 @@ test "index should render correct template and layout" do
end
```
-Note that you cannot test for template and layout at the same time, with one call to +assert_template+ method.
-Also, for the +layout+ test, you can give a regular expression instead of a string, but using the string, makes
+Note that you cannot test for template and layout at the same time, with one call to `assert_template` method.
+Also, for the `layout` test, you can give a regular expression instead of a string, but using the string, makes
things clearer. On the other hand, you have to include the "layouts" directory name even if you save your layout
file in this standard layout directory. Hence,
@@ -545,11 +545,11 @@ test "new should render correct layout" do
end
```
-is the correct way to assert for the layout when the view renders a partial with name +_form+. Omitting the +:partial+ key in your +assert_template+ call will complain.
+is the correct way to assert for the layout when the view renders a partial with name `_form`. Omitting the `:partial` key in your `assert_template` call will complain.
### A Fuller Functional Test Example
-Here's another example that uses +flash+, +assert_redirected_to+, and +assert_difference+:
+Here's another example that uses `flash`, `assert_redirected_to`, and `assert_difference`:
```ruby
test "should create post" do
@@ -563,15 +563,15 @@ end
### Testing Views
-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.
+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.
-NOTE: You may find references to +assert_tag+ in other documentation, but this is now deprecated in favor of +assert_select+.
+NOTE: You may find references to `assert_tag` in other documentation, but this is now deprecated in favor of `assert_select`.
-There are two forms of +assert_select+:
+There are two forms of `assert_select`:
-+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.
+`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.
-+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.
+`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.
For example, you could verify the contents on the title element in your response with:
@@ -579,7 +579,7 @@ For example, you could verify the contents on the title element in your response
assert_select 'title', "Welcome to Rails Testing Guide"
```
-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:
+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:
```ruby
assert_select 'ul.navigation' do
@@ -587,7 +587,7 @@ assert_select 'ul.navigation' do
end
```
-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.
+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.
```ruby
assert_select "ol" do |elements|
@@ -601,18 +601,18 @@ assert_select "ol" do
end
```
-The +assert_select+ assertion is quite powerful. For more advanced usage, refer to its "documentation":http://api.rubyonrails.org/classes/ActionDispatch/Assertions/SelectorAssertions.html.
+The `assert_select` assertion is quite powerful. For more advanced usage, refer to its "documentation":http://api.rubyonrails.org/classes/ActionDispatch/Assertions/SelectorAssertions.html.
#### Additional View-Based Assertions
There are more assertions that are primarily used in testing views:
|_.Assertion |_.Purpose|
-|+assert_select_email+ |Allows you to make assertions on the body of an e-mail. |
-|+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.|
-|+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.|
+|`assert_select_email` |Allows you to make assertions on the body of an e-mail. |
+|`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.|
+|`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.|
-Here's an example of using +assert_select_email+:
+Here's an example of using `assert_select_email`:
```ruby
assert_select_email do
@@ -648,25 +648,25 @@ class UserFlowsTest < ActionDispatch::IntegrationTest
end
```
-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.
+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.
### Helpers Available for Integration Tests
In addition to the standard testing helpers, there are some additional helpers available to integration tests:
|_.Helper |_.Purpose|
-|+https?+ |Returns +true+ if the session is mimicking a secure HTTPS request.|
-|+https!+ |Allows you to mimic a secure HTTPS request.|
-|+host!+ |Allows you to set the host name to use in the next request.|
-|+redirect?+ |Returns +true+ if the last request was a redirect.|
-|+follow_redirect!+ |Follows a single redirect response.|
-|+request_via_redirect(http_method, path, [parameters], [headers])+ |Allows you to make an HTTP request and follow any subsequent redirects.|
-|+post_via_redirect(path, [parameters], [headers])+ |Allows you to make an HTTP POST request and follow any subsequent redirects.|
-|+get_via_redirect(path, [parameters], [headers])+ |Allows you to make an HTTP GET request and follow any subsequent redirects.|
-|+patch_via_redirect(path, [parameters], [headers])+ |Allows you to make an HTTP PATCH request and follow any subsequent redirects.|
-|+put_via_redirect(path, [parameters], [headers])+ |Allows you to make an HTTP PUT request and follow any subsequent redirects.|
-|+delete_via_redirect(path, [parameters], [headers])+ |Allows you to make an HTTP DELETE request and follow any subsequent redirects.|
-|+open_session+ |Opens a new session instance.|
+|`https?` |Returns `true` if the session is mimicking a secure HTTPS request.|
+|`https!` |Allows you to mimic a secure HTTPS request.|
+|`host!` |Allows you to set the host name to use in the next request.|
+|`redirect?` |Returns `true` if the last request was a redirect.|
+|`follow_redirect!` |Follows a single redirect response.|
+|`request_via_redirect(http_method, path, [parameters], [headers])` |Allows you to make an HTTP request and follow any subsequent redirects.|
+|`post_via_redirect(path, [parameters], [headers])` |Allows you to make an HTTP POST request and follow any subsequent redirects.|
+|`get_via_redirect(path, [parameters], [headers])` |Allows you to make an HTTP GET request and follow any subsequent redirects.|
+|`patch_via_redirect(path, [parameters], [headers])` |Allows you to make an HTTP PATCH request and follow any subsequent redirects.|
+|`put_via_redirect(path, [parameters], [headers])` |Allows you to make an HTTP PUT request and follow any subsequent redirects.|
+|`delete_via_redirect(path, [parameters], [headers])` |Allows you to make an HTTP DELETE request and follow any subsequent redirects.|
+|`open_session` |Opens a new session instance.|
### Integration Testing Examples
@@ -754,28 +754,28 @@ Rake Tasks for Running your Tests
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.
|_.Tasks |_.Description|
-|+rake test+ |Runs all unit, functional and integration tests. You can also simply run +rake+ as the _test_ target is the default.|
-|+rake test:benchmark+ |Benchmark the performance tests|
-|+rake test:functionals+ |Runs all the functional tests from +test/functional+|
-|+rake test:integration+ |Runs all the integration tests from +test/integration+|
-|+rake test:profile+ |Profile the performance tests|
-|+rake test:recent+ |Tests recent changes|
-|+rake test:uncommitted+ |Runs all the tests which are uncommitted. Supports Subversion and Git|
-|+rake test:units+ |Runs all the unit tests from +test/unit+|
+|`rake test` |Runs all unit, functional and integration tests. You can also simply run `rake` as the _test_ target is the default.|
+|`rake test:benchmark` |Benchmark the performance tests|
+|`rake test:functionals` |Runs all the functional tests from `test/functional`|
+|`rake test:integration` |Runs all the integration tests from `test/integration`|
+|`rake test:profile` |Profile the performance tests|
+|`rake test:recent` |Tests recent changes|
+|`rake test:uncommitted` |Runs all the tests which are uncommitted. Supports Subversion and Git|
+|`rake test:units` |Runs all the unit tests from `test/unit`|
-Brief Note About +Test::Unit+
+Brief Note About `Test::Unit`
-----------------------------
-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
+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
us to use all of the basic assertions in our tests.
-NOTE: For more information on +Test::Unit+, refer to "test/unit Documentation":http://ruby-doc.org/stdlib/libdoc/test/unit/rdoc/
+NOTE: For more information on `Test::Unit`, refer to "test/unit Documentation":http://ruby-doc.org/stdlib/libdoc/test/unit/rdoc/
Setup and Teardown
------------------
-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:
+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:
```ruby
require 'test_helper'
@@ -811,14 +811,14 @@ class PostsControllerTest < ActionController::TestCase
end
```
-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:
+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:
* a block
* a method (like in the earlier example)
* a method name as a symbol
* a lambda
-Let's see the earlier example by specifying +setup+ callback by specifying a method name as a symbol:
+Let's see the earlier example by specifying `setup` callback by specifying a method name as a symbol:
```ruby
require '../test_helper'
@@ -863,7 +863,7 @@ end
Testing Routes
--------------
-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:
+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:
```ruby
test "should route to post" do
@@ -896,13 +896,13 @@ In order to test that your mailer is working as expected, you can use unit tests
#### Revenge of the Fixtures
-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.
+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.
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.
#### The Basic Test Case
-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.
+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.
```ruby
require 'test_helper'
@@ -922,9 +922,9 @@ class UserMailerTest < ActionMailer::TestCase
end
```
-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.
+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.
-Here's the content of the +invite+ fixture:
+Here's the content of the `invite` fixture:
```
Hi friend@example.com,
@@ -934,7 +934,7 @@ You have been invited.
Cheers!
```
-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+).
+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`).
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.
@@ -962,10 +962,10 @@ end
Other Testing Approaches
------------------------
-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:
+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:
* "NullDB":http://avdi.org/projects/nulldb/, a way to speed up testing by avoiding database use.
* "Factory Girl":https://github.com/thoughtbot/factory_girl/tree/master, a replacement for fixtures.
* "Machinist":https://github.com/notahat/machinist/tree/master, another replacement for fixtures.
-* "Shoulda":http://www.thoughtbot.com/projects/shoulda, an extension to +test/unit+ with additional helpers, macros, and assertions.
+* "Shoulda":http://www.thoughtbot.com/projects/shoulda, an extension to `test/unit` with additional helpers, macros, and assertions.
* "RSpec":http://relishapp.com/rspec, a behavior-driven development framework