testing.md 61.6 KB
Newer Older
1
**DO NOT READ THIS FILE ON GITHUB, GUIDES ARE PUBLISHED ON http://guides.rubyonrails.org.**
X
Xavier Noria 已提交
2

3 4 5
A Guide to Testing Rails Applications
=====================================

6
This guide covers built-in mechanisms in Rails for testing your application.
7 8

After reading this guide, you will know:
9

10
* Rails testing terminology.
E
eileencodes 已提交
11
* How to write unit, functional, integration, and system tests for your application.
12
* Other popular testing approaches and plugins.
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27

--------------------------------------------------------------------------------

Why Write Tests for your Rails Applications?
--------------------------------------------

Rails makes it super easy to write your tests. It starts by producing skeleton test code while you are creating your models and controllers.

By simply running your Rails tests you can ensure your code adheres to the desired functionality even after some major code refactoring.

Rails tests can also simulate browser requests and thus you can test your application's response without having to test it through your browser.

Introduction to Testing
-----------------------

28
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.
29 30 31

### Rails Sets up for Testing from the Word Go

Z
Zachary Scott 已提交
32
Rails creates a `test` directory for you as soon as you create a Rails project using `rails new` _application_name_. If you list the contents of this directory then you shall see:
33 34 35

```bash
$ ls -F test
E
eileencodes 已提交
36
controllers/           helpers/               mailers/               system/                test_helper.rb
37
fixtures/              integration/           models/                application_system_test_case.rb
38 39
```

40
The `helpers`, `mailers`, and `models` directories are meant to hold tests for view helpers, mailers, and models, respectively. The `controllers` directory is meant to hold tests for controllers, routes, and views. The `integration` directory is meant to hold tests for interactions between controllers.
41

E
eileencodes 已提交
42 43 44
The system test directory holds system tests, which are used for full browser
testing of your application. System tests allow you to test your application
the way your users experience it and help you test your JavaScript as well.
E
eileencodes 已提交
45 46 47
System tests inherit from Capybara and perform in browser tests for your
application.

Z
Zachary Scott 已提交
48
Fixtures are a way of organizing test data; they reside in the `fixtures` directory.
49

50 51
A `jobs` directory will also be created when an associated test is first generated.

52 53
The `test_helper.rb` file holds the default configuration for your tests.

54
The `application_system_test_case.rb` holds the default configuration for your system
E
eileencodes 已提交
55 56
tests.

57

58
### The Test Environment
59

60
By default, every Rails application has three environments: development, test, and production.
61

62
Each environment's configuration can be modified similarly. In this case, we can modify our test environment by changing the options found in `config/environments/test.rb`.
63

64
NOTE: Your tests are run under `RAILS_ENV=test`.
65

66
### Rails meets Minitest
67

68
If you remember, we used the `rails generate model` command in the
69
[Getting Started with Rails](getting_started.html) guide. We created our first
70
model, and among other things it created test stubs in the `test` directory:
71 72

```bash
73
$ bin/rails generate model article title:string body:text
74
...
75 76 77
create  app/models/article.rb
create  test/models/article_test.rb
create  test/fixtures/articles.yml
78 79 80
...
```

81
The default test stub in `test/models/article_test.rb` looks like this:
82 83 84 85

```ruby
require 'test_helper'

86
class ArticleTest < ActiveSupport::TestCase
P
Prem Sichanugrist 已提交
87 88 89
  # test "the truth" do
  #   assert true
  # end
90 91 92 93 94 95 96 97 98
end
```

A line by line examination of this file will help get you oriented to Rails testing code and terminology.

```ruby
require 'test_helper'
```

99
By requiring this file, `test_helper.rb` the default configuration to run our tests is loaded. We will include this with all the tests we write, so any methods added to this file are available to all our tests.
100 101

```ruby
102
class ArticleTest < ActiveSupport::TestCase
103 104
```

105
The `ArticleTest` class defines a _test case_ because it inherits from `ActiveSupport::TestCase`. `ArticleTest` thus has all the methods available from `ActiveSupport::TestCase`. Later in this guide, we'll see some of the methods it gives us.
106

107
Any method defined within a class inherited from `Minitest::Test`
108
(which is the superclass of `ActiveSupport::TestCase`) that begins with `test_` (case sensitive) is simply called a test. So, methods defined as `test_password` and `test_valid_password` are legal test names and are run automatically when the test case is run.
109

110
Rails also adds a `test` method that takes a test name and a block. It generates a normal `Minitest::Unit` test with method names prefixed with `test_`. So you don't have to worry about naming the methods, and you can write something like:
111 112 113 114 115 116 117

```ruby
test "the truth" do
  assert true
end
```

118
Which is approximately the same as writing this:
119 120 121 122 123 124 125

```ruby
def test_the_truth
  assert true
end
```

126
However only the `test` macro allows a more readable test name. You can still use regular method definitions though.
127

128 129 130
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. This may require use of `define_method` and `send` calls to function properly, but formally there's little restriction on the name.

Next, let's look at our first assertion:
131 132 133 134 135

```ruby
assert true
```

136
An assertion is a line of code that evaluates an object (or expression) for expected results. For example, an assertion can check:
137 138 139 140 141 142

* does this value = that value?
* is this object nil?
* does this line of code throw an exception?
* is the user's password greater than 5 characters?

143
Every test may contain one or more assertions, with no restriction as to how many assertions are allowed. Only when all the assertions are successful will the test pass.
144

145 146
#### Your first failing test

147
To see how a test failure is reported, you can add a failing test to the `article_test.rb` test case.
148 149

```ruby
150 151 152
test "should not save article without title" do
  article = Article.new
  assert_not article.save
153 154 155
end
```

156
Let us run this newly added test (where `6` is the number of line where the test is defined).
157 158

```bash
159
$ bin/rails test test/models/article_test.rb:6
160 161 162 163
Run options: --seed 44656

# Running:

164
F
P
Prem Sichanugrist 已提交
165

166 167 168
Failure:
ArticleTest#test_should_not_save_article_without_title [/path/to/blog/test/models/article_test.rb:6]:
Expected true to be nil or false
169 170


171 172 173 174 175 176 177 178
bin/rails test test/models/article_test.rb:6



Finished in 0.023918s, 41.8090 runs/s, 41.8090 assertions/s.

1 runs, 1 assertions, 1 failures, 0 errors, 0 skips

179 180
```

181
In the output, `F` denotes a failure. You can see the corresponding trace shown under `Failure` along with the name of the failing test. The next few lines contain the stack trace followed by a message that 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:
182 183

```ruby
184 185 186
test "should not save article without title" do
  article = Article.new
  assert_not article.save, "Saved the article without a title"
187 188 189 190 191 192
end
```

Running this test shows the friendlier assertion message:

```bash
193 194
Failure:
ArticleTest#test_should_not_save_article_without_title [/path/to/blog/test/models/article_test.rb:6]:
195
Saved the article without a title
196 197 198 199 200
```

Now to get this test to pass we can add a model level validation for the _title_ field.

```ruby
201
class Article < ApplicationRecord
202
  validates :title, presence: true
203 204 205 206 207 208
end
```

Now the test should pass. Let us verify by running the test again:

```bash
209
$ bin/rails test test/models/article_test.rb:6
210 211 212 213
Run options: --seed 31252

# Running:

214 215
.

216
Finished in 0.027476s, 36.3952 runs/s, 36.3952 assertions/s.
P
Prem Sichanugrist 已提交
217

218
1 runs, 1 assertions, 0 failures, 0 errors, 0 skips
219 220
```

221 222 223 224 225
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)](http://c2.com/cgi/wiki?TestDrivenDevelopment).
226

227 228
#### What an error looks like

229 230 231 232 233 234 235 236 237 238 239 240 241
To see how an error gets reported, here's a test containing an error:

```ruby
test "should report error" do
  # some_undefined_variable is not defined elsewhere in the test case
  some_undefined_variable
  assert true
end
```

Now you can see even more output in the console from running the tests:

```bash
242
$ bin/rails test test/models/article_test.rb
243 244 245 246 247 248 249 250
Run options: --seed 1808

# Running:

.E

Error:
ArticleTest#test_should_report_error:
S
Shia 已提交
251 252
NameError: undefined local variable or method 'some_undefined_variable' for #<ArticleTest:0x007fee3aa71798>
    test/models/article_test.rb:11:in 'block in <class:ArticleTest>'
253 254 255


bin/rails test test/models/article_test.rb:9
P
Prem Sichanugrist 已提交
256

257 258


259 260 261
Finished in 0.040609s, 49.2500 runs/s, 24.6250 assertions/s.

2 runs, 1 assertions, 0 failures, 1 errors, 0 skips
262 263 264 265
```

Notice the 'E' in the output. It denotes a test with error.

266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
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 random order. The
[`config.active_support.test_order` option](configuring.html#configuring-active-support)
can be used to configure test order.

When a test fails you are presented with the corresponding backtrace. By default
Rails filters that backtrace and will only print lines relevant to your
application. This eliminates the framework noise and helps to focus on your
code. However there are situations when you want to see the full
backtrace. Simply set the `-b` (or `--backtrace`) argument to enable this behavior:

```bash
$ bin/rails test -b test/models/article_test.rb
```

If we want this test to pass we can modify it to use `assert_raises` like so:

```ruby
test "should report error" do
  # some_undefined_variable is not defined elsewhere in the test case
  assert_raises(NameError) do
    some_undefined_variable
  end
end
```

This test should now pass.

### Available Assertions

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.

Here's an extract of the assertions you can use with
[`Minitest`](https://github.com/seattlerb/minitest), the default testing library
used by Rails. The `[msg]` parameter is an optional string message you can
302
specify to make your test failure messages clearer.
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338

| Assertion                                                        | Purpose |
| ---------------------------------------------------------------- | ------- |
| `assert( test, [msg] )`                                          | Ensures that `test` is true.|
| `assert_not( test, [msg] )`                                      | Ensures that `test` is false.|
| `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 false.|
| `assert_nil( obj, [msg] )`                                       | Ensures that `obj.nil?` is true.|
| `assert_not_nil( obj, [msg] )`                                   | Ensures that `obj.nil?` is false.|
| `assert_empty( obj, [msg] )`                                     | Ensures that `obj` is `empty?`.|
| `assert_not_empty( obj, [msg] )`                                 | Ensures that `obj` is not `empty?`.|
| `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_includes( collection, obj, [msg] )`                      | Ensures that `obj` is in `collection`.|
| `assert_not_includes( collection, obj, [msg] )`                  | Ensures that `obj` is not in `collection`.|
| `assert_in_delta( expected, actual, [delta], [msg] )`            | Ensures that the numbers `expected` and `actual` are within `delta` of each other.|
| `assert_not_in_delta( expected, actual, [delta], [msg] )`        | Ensures that the numbers `expected` and `actual` are not within `delta` of each other.|
| `assert_throws( symbol, [msg] ) { block }`                       | Ensures that the given block throws the symbol.|
| `assert_raises( exception1, exception2, ... ) { block }`         | Ensures that the given block raises one of the given exceptions.|
| `assert_instance_of( class, obj, [msg] )`                        | Ensures that `obj` is an instance of `class`.|
| `assert_not_instance_of( class, obj, [msg] )`                    | Ensures that `obj` is not an instance of `class`.|
| `assert_kind_of( class, obj, [msg] )`                            | Ensures that `obj` is an instance of `class` or is descending from it.|
| `assert_not_kind_of( class, obj, [msg] )`                        | Ensures that `obj` is not an instance of `class` and is not descending from it.|
| `assert_respond_to( obj, symbol, [msg] )`                        | Ensures that `obj` responds to `symbol`.|
| `assert_not_respond_to( obj, symbol, [msg] )`                    | Ensures that `obj` does not respond to `symbol`.|
| `assert_operator( obj1, operator, [obj2], [msg] )`               | Ensures that `obj1.operator(obj2)` is true.|
| `assert_not_operator( obj1, operator, [obj2], [msg] )`           | Ensures that `obj1.operator(obj2)` is false.|
| `assert_predicate ( obj, predicate, [msg] )`                     | Ensures that `obj.predicate` is true, e.g. `assert_predicate str, :empty?`|
| `assert_not_predicate ( obj, predicate, [msg] )`                 | Ensures that `obj.predicate` is false, e.g. `assert_not_predicate str, :empty?`|
| `flunk( [msg] )`                                                 | Ensures failure. This is useful to explicitly mark a test that isn't finished yet.|

The above are a subset of assertions that minitest supports. For an exhaustive &
more up-to-date list, please check
[Minitest API documentation](http://docs.seattlerb.org/minitest/), specifically
339
[`Minitest::Assertions`](http://docs.seattlerb.org/minitest/Minitest/Assertions.html).
340 341 342 343 344 345 346 347 348 349 350

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.

NOTE: Creating your own assertions is an advanced topic that we won't cover in this tutorial.

### Rails Specific Assertions

Rails adds some custom assertions of its own to the `minitest` framework:

| Assertion                                                                         | Purpose |
| --------------------------------------------------------------------------------- | ------- |
351 352
| [`assert_difference(expressions, difference = 1, message = nil) {...}`](http://api.rubyonrails.org/classes/ActiveSupport/Testing/Assertions.html#method-i-assert_difference) | 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, &block)`](http://api.rubyonrails.org/classes/ActiveSupport/Testing/Assertions.html#method-i-assert_no_difference) | Asserts that the numeric result of evaluating an expression is not changed before and after invoking the passed in block.|
353
| [`assert_nothing_raised { block }`](http://api.rubyonrails.org/classes/ActiveSupport/TestCase.html#method-i-assert_nothing_raised) | Ensures that the given block doesn't raise any exceptions.|
354 355 356 357
| [`assert_recognizes(expected_options, path, extras={}, message=nil)`](http://api.rubyonrails.org/classes/ActionDispatch/Assertions/RoutingAssertions.html#method-i-assert_recognizes) | 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)`](http://api.rubyonrails.org/classes/ActionDispatch/Assertions/RoutingAssertions.html#method-i-assert_generates) | 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)`](http://api.rubyonrails.org/classes/ActionDispatch/Assertions/ResponseAssertions.html#method-i-assert_response) | Asserts that the response comes with a specific status code. You can specify `:success` to indicate 200-299, `:redirect` to indicate 300-399, `:missing` to indicate 404, or `:error` to match the 500-599 range. You can also pass an explicit status number or its symbolic equivalent. For more information, see [full list of status codes](http://rubydoc.info/github/rack/rack/master/Rack/Utils#HTTP_STATUS_CODES-constant) and how their [mapping](http://rubydoc.info/github/rack/rack/master/Rack/Utils#SYMBOL_TO_STATUS_CODE-constant) works.|
| [`assert_redirected_to(options = {}, message=nil)`](http://api.rubyonrails.org/classes/ActionDispatch/Assertions/ResponseAssertions.html#method-i-assert_redirected_to) | Asserts that the redirection options passed in match those of the redirect called in the latest action. This match can be partial, such that `assert_redirected_to(controller: "weblog")` will also match the redirection of `redirect_to(controller: "weblog", action: "show")` and so on. You can also pass named routes such as `assert_redirected_to root_path` and Active Record objects such as `assert_redirected_to @article`.|
358 359 360 361 362 363 364

You'll see the usage of some of these assertions in the next chapter.

### A Brief Note About Test Cases

All the basic assertions such as `assert_equal` defined in `Minitest::Assertions` are also available in the classes we use in our own test cases. In fact, Rails provides the following classes for you to inherit from:

365 366 367 368 369
* [`ActiveSupport::TestCase`](http://api.rubyonrails.org/classes/ActiveSupport/TestCase.html)
* [`ActionMailer::TestCase`](http://api.rubyonrails.org/classes/ActionMailer/TestCase.html)
* [`ActionView::TestCase`](http://api.rubyonrails.org/classes/ActionView/TestCase.html)
* [`ActionDispatch::IntegrationTest`](http://api.rubyonrails.org/classes/ActionDispatch/IntegrationTest.html)
* [`ActiveJob::TestCase`](http://api.rubyonrails.org/classes/ActiveJob/TestCase.html)
E
eileencodes 已提交
370
* [`ActionDispatch::SystemTestCase`](http://api.rubyonrails.org/classes/ActionDispatch/SystemTestCase.html)
371 372 373

Each of these classes include `Minitest::Assertions`, allowing us to use all of the basic assertions in our tests.

374 375
NOTE: For more information on `Minitest`, refer to [its
documentation](http://docs.seattlerb.org/minitest).
376 377 378

### The Rails Test Runner

379
We can run all of our tests at once by using the `bin/rails test` command.
380

S
Shia 已提交
381
Or we can run a single test file by passing the `bin/rails test` command the filename containing the test cases.
382 383 384

```bash
$ bin/rails test test/models/article_test.rb
385
Run options: --seed 1559
386

387
# Running:
388

389 390 391 392 393
..

Finished in 0.027034s, 73.9810 runs/s, 110.9715 assertions/s.

2 runs, 3 assertions, 0 failures, 0 errors, 0 skips
394 395 396 397
```

This will run all test methods from the test case.

398 399
You can also run a particular test method from the test case by providing the
`-n` or `--name` flag and the test's method name.
400 401 402

```bash
$ bin/rails test test/models/article_test.rb -n test_the_truth
403 404 405 406
Run options: -n test_the_truth --seed 43583

# Running:

407 408 409 410 411 412 413 414 415 416
.

Finished tests in 0.009064s, 110.3266 tests/s, 110.3266 assertions/s.

1 tests, 1 assertions, 0 failures, 0 errors, 0 skips
```

You can also run a test at a specific line by providing the line number.

```bash
417
$ bin/rails test test/models/article_test.rb:6 # run specific test and line
418 419 420 421 422 423 424 425
```

You can also run an entire directory of tests by providing the path to the directory.

```bash
$ bin/rails test test/controllers # run all tests from specific directory
```

426
The test runner also provides a lot of other features like failing fast, deferring test output
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
at the end of test run and so on. Check the documentation of the test runner as follows:

```bash
$ bin/rails test -h
minitest options:
    -h, --help                       Display this help.
    -s, --seed SEED                  Sets random seed. Also via env. Eg: SEED=n rake
    -v, --verbose                    Verbose. Show progress processing files.
    -n, --name PATTERN               Filter run on /regexp/ or string.
        --exclude PATTERN            Exclude /regexp/ or string from run.

Known extensions: rails, pride

Usage: bin/rails test [options] [files or directories]
You can run a single test by appending a line number to a filename:

    bin/rails test test/models/user_test.rb:27

You can run multiple files and directories at the same time:

    bin/rails test test/controllers test/integration/login_test.rb

By default test failures and errors are reported inline during a run.

Rails options:
    -e, --environment ENV            Run tests in the ENV environment
    -b, --backtrace                  Show the complete backtrace
    -d, --defer-output               Output test failures and errors after the test run
    -f, --fail-fast                  Abort test run on first failure or error
    -c, --[no-]color                 Enable color in the output
```
458 459 460 461 462 463 464 465 466 467 468 469 470 471 472

The Test Database
-----------------

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.

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. This way your tests can mangle test data with confidence, without worrying about the data in the development or production databases.


### Maintaining the test database schema

In order to run your tests, your test database will need to have the current
structure. The test helper checks whether your test database has any pending
V
Vipul A M 已提交
473
migrations. It will try to load your `db/schema.rb` or `db/structure.sql`
474 475
into the test database. If migrations are still pending, an error will be
raised. Usually this indicates that your schema is not fully migrated. Running
476
the migrations against the development database (`bin/rails db:migrate`) will
477 478
bring the schema up to date.

V
Vipul A M 已提交
479
NOTE: If there were modifications to existing migrations, the test database needs to
480
be rebuilt. This can be done by executing `bin/rails db:test:prepare`.
481 482 483 484 485 486 487 488 489 490 491

### The Low-Down on Fixtures

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.
You can find comprehensive documentation in the [Fixtures API documentation](http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html).

#### What Are Fixtures?

_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 written in YAML. There is one file per model.

492 493
NOTE: Fixtures are not designed to create every object that your tests need, and are best managed when only used for default data that can be applied to the common case.

494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
You'll find fixtures under your `test/fixtures` directory. When you run `rails generate model` to create a new model, Rails automatically creates fixture stubs in this directory.

#### YAML

YAML-formatted fixtures are a 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:

```yaml
# lo & behold! I am a YAML comment!
david:
  name: David Heinemeier Hansson
  birthday: 1979-10-15
  profession: Systems development

steve:
  name: Steve Ross Kellock
  birthday: 1974-09-27
  profession: guy with keyboard
```

Each fixture is given a name followed by an indented list of colon-separated key/value pairs. Records are typically separated by a blank line. You can place comments in a fixture file by using the # character in the first column.

If you are working with [associations](/association_basics.html), you can simply
define a reference node between two different fixtures. Here's an example with
a `belongs_to`/`has_many` association:

```yaml
# In fixtures/categories.yml
about:
  name: About

# In fixtures/articles.yml
V
Vipul A M 已提交
527
first:
528 529 530 531 532
  title: Welcome to Rails!
  body: Hello world!
  category: about
```

V
Vipul A M 已提交
533
Notice the `category` key of the `first` article found in `fixtures/articles.yml` has a value of `about`. This tells Rails to load the category `about` found in `fixtures/categories.yml`.
534

V
Vipul A M 已提交
535
NOTE: For associations to reference one another by name, you can use the fixture name instead of specifying the `id:` attribute on the associated fixtures. Rails will auto assign a primary key to be consistent between runs. For more information on this association behavior please read the [Fixtures API documentation](http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html).
536 537 538 539 540 541 542 543 544 545 546 547 548 549 550

#### ERB'in It Up

ERB allows you to embed Ruby code within templates. The YAML fixture format is pre-processed with ERB when Rails loads fixtures. This allows you to use Ruby to help you generate some sample data. For example, the following code generates a thousand users:

```erb
<% 1000.times do |n| %>
user_<%= n %>:
  username: <%= "user#{n}" %>
  email: <%= "user#{n}@example.com" %>
<% end %>
```

#### Fixtures in Action

551 552
Rails automatically loads all fixtures from the `test/fixtures` directory by
default. Loading involves three steps:
553 554 555 556 557

1. Remove any existing data from the table corresponding to the fixture
2. Load the fixture data into the table
3. Dump the fixture data into a method in case you want to access it directly

558
TIP: In order to remove existing data from the database, Rails tries to disable referential integrity triggers (like foreign keys and check constraints). If you are getting annoying permission errors on running tests, make sure the database user has privilege to disable these triggers in testing environment. (In PostgreSQL, only superusers can disable all triggers. Read more about PostgreSQL permissions [here](http://blog.endpoint.com/2012/10/postgres-system-triggers-error.html)).
559 560 561 562 563 564 565 566 567 568 569 570 571

#### Fixtures are Active Record objects

Fixtures are instances of Active Record. As mentioned in point #3 above, you can access the object directly because it is automatically available as a method whose scope is local of the test case. For example:

```ruby
# this will return the User object for the fixture named david
users(:david)

# this will return the property for david called id
users(:david).id

# one can also access methods available on the User class
572 573
david = users(:david)
david.call(david.partner)
574 575 576 577 578 579 580 581 582 583 584 585 586 587 588
```

To get multiple fixtures at once, you can pass in a list of fixture names. For example:

```ruby
# this will return an array containing the fixtures david and steve
users(:david, :steve)
```


Model Testing
-------------

Model tests are used to test the various models of your application.

589 590
Rails model tests are stored under the `test/models` directory. Rails provides
a generator to create a model test skeleton for you.
591 592 593 594 595 596 597

```bash
$ bin/rails generate test_unit:model article title:string body:text
create  test/models/article_test.rb
create  test/fixtures/articles.yml
```

598
Model tests don't have their own superclass like `ActionMailer::TestCase` instead they inherit from [`ActiveSupport::TestCase`](http://api.rubyonrails.org/classes/ActiveSupport/TestCase.html).
599

E
eileencodes 已提交
600 601 602
System Testing
--------------

E
eileencodes 已提交
603 604 605
System tests are full-browser tests that can be used to test your application's
JavaScript and user experience. System tests use Capybara as a base.

E
eileencodes 已提交
606
System tests allow for running tests in either a real browser or a headless
E
eileencodes 已提交
607
driver for testing full user interactions with your application.
E
eileencodes 已提交
608 609

For creating Rails system tests, you use the `test/system` directory in your
610
application. Rails provides a generator to create a system test skeleton for you.
E
eileencodes 已提交
611 612

```bash
613
$ bin/rails generate system_test users_create
E
eileencodes 已提交
614
      invoke test_unit
615
      create test/system/users_creates_test.rb
E
eileencodes 已提交
616 617 618 619 620
```

Here's what a freshly-generated system test looks like:

```ruby
621
require "application_system_test_case"
E
eileencodes 已提交
622

623 624 625 626 627 628
class UsersCreatesTest < ApplicationSystemTestCase
  # test "visiting the index" do
  #   visit users_creates_url
  #
  #   assert_selector "h1", text: "UsersCreate"
  # end
E
eileencodes 已提交
629 630 631
end
```

E
eileencodes 已提交
632
By default, system tests are run with the Selenium driver, using the Chrome
E
eileencodes 已提交
633 634
browser, and a screen size of 1400x1400. The next section explains how to
change the default settings.
E
eileencodes 已提交
635 636 637

### Changing the default settings

638
Rails makes changing the default settings for system tests very simple. All
E
eileencodes 已提交
639
the setup is abstracted away so you can focus on writing your tests.
E
eileencodes 已提交
640

K
kenta-s 已提交
641
When you generate a new application or scaffold, an `application_system_test_case.rb` file
E
eileencodes 已提交
642 643
is created in the test directory. This is where all the configuration for your
system tests should live.
E
eileencodes 已提交
644

K
kenta-s 已提交
645
If you want to change the default settings you can simply change what the system
E
eileencodes 已提交
646 647
tests are "driven by". Say you want to change the driver from Selenium to
Poltergeist. First add the Poltergeist gem to your Gemfile. Then in your
648
`application_system_test_case.rb` file do the following:
E
eileencodes 已提交
649 650

```ruby
E
eileencodes 已提交
651 652
require "test_helper"
require "capybara/poltergeist"
E
eileencodes 已提交
653

E
eileencodes 已提交
654
class ApplicationSystemTestCase < ActionDispatch::SystemTestCase
E
eileencodes 已提交
655
  driven_by :poltergeist
E
eileencodes 已提交
656 657 658
end
```

659 660 661 662
The driver name is a required argument for `driven_by`. The optional arguments
that can be passed to `driven_by` are `:using` for the browser (this will only
be used for non-headless drivers like Selenium), `:on` for the port Puma should
use, and `:screen_size` to change the size of the screen for screenshots.
E
eileencodes 已提交
663 664

```ruby
E
eileencodes 已提交
665
require "test_helper"
E
eileencodes 已提交
666

E
eileencodes 已提交
667
class ApplicationSystemTestCase < ActionDispatch::SystemTestCase
E
eileencodes 已提交
668
  driven_by :selenium, using: :firefox
E
eileencodes 已提交
669 670 671 672
end
```

If your Capybara configuration requires more setup than provided by Rails, all
673
of that configuration can be put into the `application_system_test_case.rb` file.
E
eileencodes 已提交
674

E
eileencodes 已提交
675 676
Please see [Capybara's documentation](https://github.com/teamcapybara/capybara#setup)
for additional settings.
E
eileencodes 已提交
677

E
eileencodes 已提交
678
### Screenshot Helper
E
eileencodes 已提交
679

E
eileencodes 已提交
680
The `ScreenshotHelper` is a helper designed to capture screenshots of your tests.
E
eileencodes 已提交
681 682 683 684
This can be helpful for viewing the browser at the point a test failed, or
to view screenshots later for debugging.

Two methods are provided: `take_screenshot` and `take_failed_screenshot`.
K
kenta-s 已提交
685
`take_failed_screenshot` is automatically included in `after_teardown` inside
E
eileencodes 已提交
686
Rails.
E
eileencodes 已提交
687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704

The `take_screenshot` helper method can be included anywhere in your tests to
take a screenshot of the browser.

### Implementing a system test

Now we're going to add a system test to our blog application. We'll demonstrate
writing a system test by visiting the index page and creating a new blog article.

If you used the scaffold generator, a system test skeleton is automatically
created for you. If you did not use the generator start by creating a system
test skeleton.

```bash
$ bin/rails generate system_test articles
```

It should have created a test file placeholder for us. With the output of the
705
previous command you should see:
E
eileencodes 已提交
706 707 708 709 710 711 712 713 714

```bash
      invoke  test_unit
      create    test/system/articles_test.rb
```

Now let's open that file and write our first assertion:

```ruby
715
require "application_system_test_case"
E
eileencodes 已提交
716

717
class ArticlesTest < ApplicationSystemTestCase
E
eileencodes 已提交
718 719
  test "viewing the index" do
    visit articles_path
720
    assert_selector "h1", text: "Articles"
E
eileencodes 已提交
721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758
  end
end
```

The test should see that there is an h1 on the articles index and pass.

Run the system tests.

```bash
bin/rails test:system
```

#### Creating articles system test

Now let's test the flow for creating a new article in our blog.

```ruby
test "creating an article" do
  visit articles_path

  click_on "New Article"

  fill_in "Title", with: "Creating an Article"
  fill_in "Body", with: "Created this article successfully!"

  click_on "Create Article"

  assert_text "Creating an Article"
end
```

The first step is to call `visit articles_path`. This will take the test to the
articles index page.

Then the `click_on "New Article"` will find the "New Article" button on the
index page. This will redirect the browser to `/articles/new`.

Then the test will fill in the title and body of the article with the specified
759
text. Once the fields are filled in, "Create Article" is clicked on which will
E
eileencodes 已提交
760 761 762 763 764 765 766 767 768 769
send a POST request to create the new article in the database.

We will be redirected back to the the articles index page and there we assert
that the text from the article title is on the articles index page.

#### Taking it further

The beauty of system testing is that it is similar to integration testing in
that it tests the user's interaction with your controller, model, and view, but
system testing is much more robust and actually tests your application as if
770
a real user were using it. Going forward, you can test anything that the user
E
eileencodes 已提交
771 772
themselves would do in your application such as commenting, deleting articles,
publishing draft articles, etc.
773 774 775 776

Integration Testing
-------------------

V
Vipul A M 已提交
777
Integration tests are used to test how various parts of your application interact. They are generally used to test important workflows within our application.
778

779
For creating Rails integration tests, we use the `test/integration` directory for our application. Rails provides a generator to create an integration test skeleton for us.
780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798

```bash
$ bin/rails generate integration_test user_flows
      exists  test/integration/
      create  test/integration/user_flows_test.rb
```

Here's what a freshly-generated integration test looks like:

```ruby
require 'test_helper'

class UserFlowsTest < ActionDispatch::IntegrationTest
  # test "the truth" do
  #   assert true
  # end
end
```

V
Vipul A M 已提交
799
Here the test is inheriting from `ActionDispatch::IntegrationTest`. This makes some additional helpers available for us to use in our integration tests.
800 801 802

### Helpers Available for Integration Tests

V
Vipul A M 已提交
803
In addition to the standard testing helpers, inheriting from `ActionDispatch::IntegrationTest` comes with some additional helpers available when writing integration tests. Let's get briefly introduced to the three categories of helpers we get to choose from.
804 805 806

For dealing with the integration test runner, see [`ActionDispatch::Integration::Runner`](http://api.rubyonrails.org/classes/ActionDispatch/Integration/Runner.html).

V
Vipul A M 已提交
807
When performing requests, we will have [`ActionDispatch::Integration::RequestHelpers`](http://api.rubyonrails.org/classes/ActionDispatch/Integration/RequestHelpers.html) available for our use.
808

V
Vipul A M 已提交
809
If we need to modify the session, or state of our integration test, take a look at [`ActionDispatch::Integration::Session`](http://api.rubyonrails.org/classes/ActionDispatch/Integration/Session.html) to help.
810 811 812 813 814 815 816 817 818 819

### Implementing an integration test

Let's add an integration test to our blog application. We'll start with a basic workflow of creating a new blog article, to verify that everything is working properly.

We'll start by generating our integration test skeleton:

```bash
$ bin/rails generate integration_test blog_flow
```
820

821
It should have created a test file placeholder for us. With the output of the
V
Vipul A M 已提交
822
previous command we should see:
823 824

```bash
825 826
      invoke  test_unit
      create    test/integration/blog_flow_test.rb
827 828
```

829
Now let's open that file and write our first assertion:
830 831

```ruby
832 833 834 835 836 837
require 'test_helper'

class BlogFlowTest < ActionDispatch::IntegrationTest
  test "can see the welcome page" do
    get "/"
    assert_select "h1", "Welcome#index"
838 839 840 841
  end
end
```

842
We will take a look at `assert_select` to query the resulting HTML of a request in the "Testing Views" section below. It is used for testing the response of our request by asserting the presence of key HTML elements and their content.
843

V
Vipul A M 已提交
844
When we visit our root path, we should see `welcome/index.html.erb` rendered for the view. So this assertion should pass.
845

846
#### Creating articles integration
847

848
How about testing our ability to create a new article in our blog and see the resulting article.
849

850 851 852 853
```ruby
test "can create an article" do
  get "/articles/new"
  assert_response :success
854

855 856 857 858 859 860 861 862
  post "/articles",
    params: { article: { title: "can create", body: "article successfully." } }
  assert_response :redirect
  follow_redirect!
  assert_response :success
  assert_select "p", "Title:\n  can create"
end
```
863

864
Let's break this test down so we can understand it.
865

866
We start by calling the `:new` action on our Articles controller. This response should be successful.
867

868
After this we make a post request to the `:create` action of our Articles controller:
869

870 871 872 873 874 875
```ruby
post "/articles",
  params: { article: { title: "can create", body: "article successfully." } }
assert_response :redirect
follow_redirect!
```
876

877
The two lines following the request are to handle the redirect we setup when creating a new article.
878

879
NOTE: Don't forget to call `follow_redirect!` if you plan to make subsequent requests after a redirect is made.
880

881
Finally we can assert that our response was successful and our new article is readable on the page.
882

883
#### Taking it further
884

885
We were able to successfully test a very small workflow for visiting our blog and creating a new article. If we wanted to take this further we could add tests for commenting, removing articles, or editing comments. Integration tests are a great place to experiment with all kinds of use-cases for our applications.
886 887


888 889 890
Functional Tests for Your Controllers
-------------------------------------

V
Vipul A M 已提交
891
In Rails, testing the various actions of a controller is a form of writing functional tests. Remember your controllers handle the incoming web requests to your application and eventually respond with a rendered view. When writing functional tests, you are testing how your actions handle the requests and the expected result or response, in some cases an HTML view.
892

V
Vipul A M 已提交
893
### What to include in your Functional Tests
894 895 896 897 898 899 900 901 902

You should test for things such as:

* was the web request successful?
* was the user redirected to the right page?
* was the user successfully authenticated?
* was the correct object stored in the response template?
* was the appropriate message displayed to the user in the view?

V
Vipul A M 已提交
903
The easiest way to see functional tests in action is to generate a controller using the scaffold generator:
904

905
```bash
S
Sean Collins 已提交
906
$ bin/rails generate scaffold_controller article title:string body:text
907 908 909 910 911 912 913 914 915
...
create  app/controllers/articles_controller.rb
...
invoke  test_unit
create    test/controllers/articles_controller_test.rb
...
```

This will generate the controller code and tests for an `Article` resource.
V
Vipul A M 已提交
916
You can take a look at the file `articles_controller_test.rb` in the `test/controllers` directory.
917 918 919

If you already have a controller and just want to generate the test scaffold code for
each of the seven default actions, you can use the following command:
920 921 922

```bash
$ bin/rails generate test_unit:scaffold article
923 924
...
invoke  test_unit
925
create test/controllers/articles_controller_test.rb
926
...
927 928
```

V
Vipul A M 已提交
929
Let's take a look at one such test, `test_should_get_index` from the file `articles_controller_test.rb`.
930 931

```ruby
932
# articles_controller_test.rb
933
class ArticlesControllerTest < ActionDispatch::IntegrationTest
934
  test "should get index" do
935
    get articles_url
936 937
    assert_response :success
  end
938 939 940
end
```

941 942
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 the right response body has been generated.
943

944
The `get` method kicks off the web request and populates the results into the `@response`. It can accept up to 6 arguments:
945

946 947
* The URI of the controller action you are requesting.
  This can be in the form of a string or a route helper (e.g. `articles_url`).
948
* `params`: option with a hash of request parameters to pass into the action
949
  (e.g. query string parameters or article variables).
950 951 952 953
* `headers`: for setting the headers that will be passed with the request.
* `env`: for customizing the request environment as needed.
* `xhr`: whether the request is Ajax request or not. Can be set to true for marking the request as Ajax.
* `as`: for encoding the request with different content type. Supports `:json` by default.
954

V
Vipul A M 已提交
955
All of these keyword arguments are optional.
956

957
Example: Calling the `:show` action, passing an `id` of 12 as the `params` and setting `HTTP_REFERER` header:
958 959

```ruby
960
get article_url, params: { id: 12 }, headers: { "HTTP_REFERER" => "http://example.com/home" }
961 962
```

963
Another example: Calling the `:update` action, passing an `id` of 12 as the `params` as an Ajax request.
964 965

```ruby
966
patch article_url, params: { id: 12 }, xhr: true
967 968
```

969
NOTE: If you try running `test_should_create_article` test from `articles_controller_test.rb` it will fail on account of the newly added model level validation and rightly so.
970

971
Let us modify `test_should_create_article` test in `articles_controller_test.rb` so that all our test pass:
972 973

```ruby
974
test "should create article" do
975
  assert_difference('Article.count') do
976
    post articles_url, params: { article: { body: 'Rails is awesome!', title: 'Hello Rails' } }
977 978
  end

979
  assert_redirected_to article_path(Article.last)
980 981 982 983 984
end
```

Now you can try running all the tests and they should pass.

985 986 987 988 989 990 991
NOTE: If you followed the steps in the Basic Authentication section, you'll need to add the following to the `setup` block to get all the tests passing:

```ruby
request.headers['Authorization'] = ActionController::HttpAuthentication::Basic.
  encode_credentials('dhh', 'secret')
```

992 993 994 995 996 997 998 999 1000 1001 1002
### 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:

* `get`
* `post`
* `patch`
* `put`
* `head`
* `delete`

1003
All of request types have equivalent methods that you can use. In a typical C.R.U.D. application you'll be using `get`, `post`, `put` and `delete` more often.
1004

1005
NOTE: Functional tests do not verify whether the specified request type is accepted by the action, we're more concerned with the result. Request tests exist for this use case to make your tests more purposeful.
1006

K
Kir Shatrov 已提交
1007 1008
### Testing XHR (AJAX) requests

1009
To test AJAX requests, you can specify the `xhr: true` option to `get`, `post`,
V
Vipul A M 已提交
1010
`patch`, `put`, and `delete` methods. For example:
K
Kir Shatrov 已提交
1011 1012

```ruby
1013
test "ajax request" do
1014
  article = articles(:one)
1015
  get article_url(article), xhr: true
K
Kir Shatrov 已提交
1016

1017 1018
  assert_equal 'hello world', @response.body
  assert_equal "text/javascript", @response.content_type
K
Kir Shatrov 已提交
1019 1020 1021
end
```

A
Alexey Markov 已提交
1022
### The Three Hashes of the Apocalypse
1023

A
Alexey Markov 已提交
1024
After a request has been made and processed, you will have 3 Hash objects ready for use:
1025

1026 1027 1028
* `cookies` - Any cookies that are set
* `flash` - Any objects living in the flash
* `session` - Any object living in session variables
1029

1030
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. For example:
1031 1032 1033 1034 1035 1036 1037 1038 1039

```ruby
flash["gordon"]               flash[:gordon]
session["shmession"]          session[:shmession]
cookies["are_good_for_u"]     cookies[:are_good_for_u]
```

### Instance Variables Available

1040
You also have access to three instance variables in your functional tests, after a request is made:
1041 1042

* `@controller` - The controller processing the request
1043 1044
* `@request` - The request object
* `@response` - The response object
1045

1046 1047 1048 1049 1050

```ruby
class ArticlesControllerTest < ActionDispatch::IntegrationTest
  test "should get index" do
    get articles_url
1051

S
Shia 已提交
1052 1053
    assert_equal "index", @controller.action_name
    assert_equal "application/x-www-form-urlencoded", @request.media_type
1054
    assert_match "Articles", @response.body
1055 1056 1057 1058
  end
end
```

1059 1060
### Setting Headers and CGI variables

1061 1062 1063
[HTTP headers](http://tools.ietf.org/search/rfc2616#section-5.3)
and
[CGI variables](http://tools.ietf.org/search/rfc3875#section-4.1)
1064
can be passed as headers:
1065 1066

```ruby
1067
# setting an HTTP Header
Y
yuuji.yaginuma 已提交
1068
get articles_url, headers: { "Content-Type": "text/plain" } # simulate the request with custom header
1069 1070

# setting a CGI variable
Y
yuuji.yaginuma 已提交
1071
get articles_url, headers: { "HTTP_REFERER": "http://example.com/home" } # simulate the request with custom env variable
1072 1073
```

1074
### Testing `flash` notices
1075

V
Vipul A M 已提交
1076
If you remember from earlier, one of the Three Hashes of the Apocalypse was `flash`.
1077 1078 1079 1080 1081

We want to add a `flash` message to our blog application whenever someone
successfully creates a new Article.

Let's start by adding this assertion to our `test_should_create_article` test:
1082 1083

```ruby
1084
test "should create article" do
R
Robin Dupret 已提交
1085
  assert_difference('Article.count') do
1086
    post article_url, params: { article: { title: 'Some title' } }
1087
  end
1088

1089
  assert_redirected_to article_path(Article.last)
1090
  assert_equal 'Article was successfully created.', flash[:notice]
1091 1092 1093
end
```

1094 1095 1096
If we run our test now, we should see a failure:

```bash
1097
$ bin/rails test test/controllers/articles_controller_test.rb -n test_should_create_article
1098 1099 1100 1101 1102 1103 1104 1105 1106
Run options: -n test_should_create_article --seed 32266

# Running:

F

Finished in 0.114870s, 8.7055 runs/s, 34.8220 assertions/s.

  1) Failure:
1107
ArticlesControllerTest#test_should_create_article [/test/controllers/articles_controller_test.rb:16]:
1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134
--- expected
+++ actual
@@ -1 +1 @@
-"Article was successfully created."
+nil

1 runs, 4 assertions, 1 failures, 0 errors, 0 skips
```

Let's implement the flash message now in our controller. Our `:create` action should now look like this:

```ruby
def create
  @article = Article.new(article_params)

  if @article.save
    flash[:notice] = 'Article was successfully created.'
    redirect_to @article
  else
    render 'new'
  end
end
```

Now if we run our tests, we should see it pass:

```bash
1135
$ bin/rails test test/controllers/articles_controller_test.rb -n test_should_create_article
1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146
Run options: -n test_should_create_article --seed 18981

# Running:

.

Finished in 0.081972s, 12.1993 runs/s, 48.7972 assertions/s.

1 runs, 4 assertions, 0 failures, 0 errors, 0 skips
```

1147 1148 1149 1150 1151 1152 1153 1154 1155
### Putting it together

At this point our Articles controller tests the `:index` as well as `:new` and `:create` actions. What about dealing with existing data?

Let's write a test for the `:show` action:

```ruby
test "should show article" do
  article = articles(:one)
1156
  get article_url(article)
1157 1158 1159 1160
  assert_response :success
end
```

V
Vipul A M 已提交
1161
Remember from our discussion earlier on fixtures, the `articles()` method will give us access to our Articles fixtures.
1162 1163 1164 1165 1166 1167 1168

How about deleting an existing Article?

```ruby
test "should destroy article" do
  article = articles(:one)
  assert_difference('Article.count', -1) do
1169
    delete article_url(article)
1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180
  end

  assert_redirected_to articles_path
end
```

We can also add a test for updating an existing Article.

```ruby
test "should update article" do
  article = articles(:one)
1181

1182
  patch article_url(article), params: { article: { title: "updated" } }
1183

1184
  assert_redirected_to article_path(article)
1185
  # Reload association to fetch updated data and assert that title is updated.
V
Vipul A M 已提交
1186
  article.reload
1187
  assert_equal "updated", article.title
1188 1189 1190 1191 1192
end
```

Notice we're starting to see some duplication in these three tests, they both access the same Article fixture data. We can D.R.Y. this up by using the `setup` and `teardown` methods provided by `ActiveSupport::Callbacks`.

V
Vipul A M 已提交
1193
Our test should now look something as what follows. Disregard the other tests for now, we're leaving them out for brevity.
1194 1195 1196 1197

```ruby
require 'test_helper'

1198
class ArticlesControllerTest < ActionDispatch::IntegrationTest
1199
  # called before every single test
1200
  setup do
1201 1202 1203 1204
    @article = articles(:one)
  end

  # called after every single test
1205
  teardown do
1206 1207
    # when controller is using cache it may be a good idea to reset it afterwards
    Rails.cache.clear
1208 1209 1210 1211
  end

  test "should show article" do
    # Reuse the @article instance variable from setup
1212
    get article_url(@article)
1213 1214 1215 1216 1217
    assert_response :success
  end

  test "should destroy article" do
    assert_difference('Article.count', -1) do
1218
      delete article_url(@article)
1219 1220 1221 1222 1223 1224
    end

    assert_redirected_to articles_path
  end

  test "should update article" do
1225
    patch article_url(@article), params: { article: { title: "updated" } }
1226

1227
    assert_redirected_to article_path(@article)
1228
    # Reload association to fetch updated data and assert that title is updated.
V
Vipul A M 已提交
1229
    @article.reload
1230
    assert_equal "updated", @article.title
1231 1232 1233 1234 1235 1236
  end
end
```

Similar to other callbacks in Rails, the `setup` and `teardown` methods can also be used by passing a block, lambda, or method name as a symbol to call.

K
Kir Shatrov 已提交
1237 1238 1239 1240 1241 1242
### Test helpers

To avoid code duplication, you can add your own test helpers.
Sign in helper can be a good example:

```ruby
S
Shia 已提交
1243
# test/test_helper.rb
K
Kir Shatrov 已提交
1244 1245

module SignInHelper
1246 1247
  def sign_in_as(user)
    post sign_in_url(email: user.email, password: user.password)
K
Kir Shatrov 已提交
1248 1249 1250
  end
end

1251
class ActionDispatch::IntegrationTest
K
Kir Shatrov 已提交
1252 1253 1254 1255 1256 1257 1258
  include SignInHelper
end
```

```ruby
require 'test_helper'

1259
class ProfileControllerTest < ActionDispatch::IntegrationTest
K
Kir Shatrov 已提交
1260 1261 1262

  test "should show profile" do
    # helper is now reusable from any controller test case
1263
    sign_in_as users(:david)
K
Kir Shatrov 已提交
1264

1265
    get profile_url
K
Kir Shatrov 已提交
1266 1267 1268 1269 1270
    assert_response :success
  end
end
```

1271 1272 1273
Testing Routes
--------------

1274
Like everything else in your Rails application, you can test your routes. Route tests reside in `test/controllers/` or are part of controller tests.
1275

1276 1277
NOTE: If your application has complex routes, Rails provides a number of useful helpers to test them.

1278 1279
For more information on routing assertions available in Rails, see the API documentation for [`ActionDispatch::Assertions::RoutingAssertions`](http://api.rubyonrails.org/classes/ActionDispatch/Assertions/RoutingAssertions.html).

1280 1281
Testing Views
-------------
1282

B
Benjamin Klotz 已提交
1283
Testing the response to your request by asserting the presence of key HTML elements and their content is a common way to test the views of your application. Like route tests, view tests reside in `test/controllers/` or are part of controller tests. The `assert_select` method allows you to query HTML elements of the response by using a simple yet powerful syntax.
1284 1285 1286

There are two forms of `assert_select`:

1287
`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) or an expression with substitution values.
1288

1289
`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 `Nokogiri::XML::Node` or `Nokogiri::XML::NodeSet`) and its descendants.
1290 1291 1292 1293 1294 1295 1296

For example, you could verify the contents on the title element in your response with:

```ruby
assert_select 'title', "Welcome to Rails Testing Guide"
```

1297 1298 1299 1300
You can also use nested `assert_select` blocks for deeper investigation.

In the following example, the inner `assert_select` for `li.menu_item` runs
within the collection of elements selected by the outer block:
1301 1302 1303 1304 1305 1306 1307

```ruby
assert_select 'ul.navigation' do
  assert_select 'li.menu_item'
end
```

1308 1309 1310
A collection of selected elements may be iterated through so that `assert_select` may be called separately for each element.

For example if the response contains two ordered lists, each with four nested list elements then the following tests will both pass.
1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323

```ruby
assert_select "ol" do |elements|
  elements.each do |element|
    assert_select element, "li", 4
  end
end

assert_select "ol" do
  assert_select "li", 8
end
```

1324
This assertion is quite powerful. For more advanced usage, refer to its [documentation](https://github.com/rails/rails-dom-testing/blob/master/lib/rails/dom/testing/assertions/selector_assertions.rb).
1325 1326 1327 1328 1329

#### Additional View-Based Assertions

There are more assertions that are primarily used in testing views:

S
Sunny Ripert 已提交
1330 1331 1332 1333 1334
| 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.|
1335 1336 1337 1338 1339 1340 1341 1342 1343

Here's an example of using `assert_select_email`:

```ruby
assert_select_email do
  assert_select 'small', 'Please click the "Unsubscribe" link if you want to opt-out.'
end
```

Y
yui-knk 已提交
1344
Testing Helpers
1345 1346
---------------

1347 1348 1349
A helper is just a simple module where you can define methods which are
available into your views.

1350 1351 1352 1353
In order to test helpers, all you need to do is check that the output of the
helper method matches what you'd expect. Tests related to the helpers are
located under the `test/helpers` directory.

1354
Given we have the following helper:
1355 1356

```ruby
1357 1358 1359 1360
module UserHelper
  def link_to_user(user)
    link_to "#{user.first_name} #{user.last_name}", user
  end
1361 1362 1363
end
```

1364
We can test the output of this method like this:
1365 1366 1367

```ruby
class UserHelperTest < ActionView::TestCase
V
Vipul A M 已提交
1368 1369
  test "should return the user's full name" do
    user = users(:david)
1370 1371

    assert_dom_equal %{<a href="/user/#{user.id}">David Heinemeier Hansson</a>}, link_to_user(user)
1372 1373 1374 1375 1376 1377 1378
  end
end
```

Moreover, since the test class extends from `ActionView::TestCase`, you have
access to Rails' helper methods such as `link_to` or `pluralize`.

1379 1380 1381 1382 1383 1384 1385
Testing Your Mailers
--------------------

Testing mailer classes requires some specific tools to do a thorough job.

### Keeping the Postman in Check

1386
Your mailer classes - like every other part of your Rails application - should be tested to ensure that they are working as expected.
1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405

The goals of testing your mailer classes are to ensure that:

* emails are being processed (created and sent)
* the email content is correct (subject, sender, body, etc)
* the right emails are being sent at the right times

#### From All Sides

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.

### Unit Testing

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.

#### 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.

V
Vipul A M 已提交
1406
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 create those files yourself.
1407 1408 1409 1410 1411 1412 1413 1414 1415 1416

#### 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.

```ruby
require 'test_helper'

class UserMailerTest < ActionMailer::TestCase
  test "invite" do
1417 1418 1419 1420
    # Create the email and store it for further assertions
    email = UserMailer.create_invite('me@example.com',
                                     'friend@example.com', Time.now)

1421
    # Send the email, then test that it got queued
1422
    assert_emails 1 do
1423
      email.deliver_now
1424
    end
1425 1426 1427 1428 1429 1430

    # Test the body of the sent email contains what we expect it to
    assert_equal ['me@example.com'], email.from
    assert_equal ['friend@example.com'], email.to
    assert_equal 'You have been invited by me@example.com', email.subject
    assert_equal read_fixture('invite').join, email.body.to_s
1431 1432 1433 1434
  end
end
```

1435 1436 1437 1438
In the test we send the email and store the returned object in the `email`
variable. We then ensure that it was sent (the first assert), then, in the
second batch of assertions, we ensure that the email does indeed contain what we
expect. The helper `read_fixture` is used to read in the content from this file.
1439

1440
NOTE: `email.body.to_s` is present when there's only one (HTML or text) part present.
1441
If the mailer provides both, you can test your fixture against specific parts
1442 1443
with `email.text_part.body.to_s` or `email.html_part.body.to_s`.

1444 1445 1446 1447 1448 1449 1450 1451 1452 1453
Here's the content of the `invite` fixture:

```
Hi friend@example.com,

You have been invited.

Cheers!
```

1454 1455 1456 1457 1458 1459
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`).
1460

1461
NOTE: The `ActionMailer::Base.deliveries` array is only reset automatically in
1462 1463 1464
`ActionMailer::TestCase` and `ActionDispatch::IntegrationTest` tests.
If you want to have a clean slate outside these test cases, you can reset it
manually with: `ActionMailer::Base.deliveries.clear`
1465 1466 1467 1468 1469 1470 1471 1472

### Functional Testing

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:

```ruby
require 'test_helper'

1473
class UserControllerTest < ActionDispatch::IntegrationTest
1474 1475
  test "invite friend" do
    assert_difference 'ActionMailer::Base.deliveries.size', +1 do
1476
      post invite_friend_url, params: { email: 'friend@example.com' }
1477 1478 1479 1480 1481
    end
    invite_email = ActionMailer::Base.deliveries.last

    assert_equal "You have been invited by me@example.com", invite_email.subject
    assert_equal 'friend@example.com', invite_email.to[0]
1482
    assert_match(/Hi friend@example.com/, invite_email.body.to_s)
1483 1484 1485 1486
  end
end
```

1487 1488 1489 1490
Testing Jobs
------------

Since your custom jobs can be queued at different levels inside your application,
V
Vipul A M 已提交
1491
you'll need to test both, the jobs themselves (their behavior when they get enqueued)
1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512
and that other entities correctly enqueue them.

### A Basic Test Case

By default, when you generate a job, an associated test will be generated as well
under the `test/jobs` directory. Here's an example test with a billing job:

```ruby
require 'test_helper'

class BillingJobTest < ActiveJob::TestCase
  test 'that account is charged' do
    BillingJob.perform_now(account, product)
    assert account.reload.charged_for?(product)
  end
end
```

This test is pretty simple and only asserts that the job get the work done
as expected.

1513 1514
By default, `ActiveJob::TestCase` will set the queue adapter to `:test` so that
your jobs are performed inline. It will also ensure that all previously performed
1515 1516 1517 1518 1519
and enqueued jobs are cleared before any test run so you can safely assume that
no jobs have already been executed in the scope of each test.

### Custom Assertions And Testing Jobs Inside Other Components

1520
Active Job ships with a bunch of custom assertions that can be used to lessen the verbosity of tests. For a full list of available assertions, see the API documentation for [`ActiveJob::TestHelper`](http://api.rubyonrails.org/classes/ActiveJob/TestHelper.html).
1521 1522 1523 1524 1525 1526 1527 1528 1529

It's a good practice to ensure that your jobs correctly get enqueued or performed
wherever you invoke them (e.g. inside your controllers). This is precisely where
the custom assertions provided by Active Job are pretty useful. For instance,
within a model:

```ruby
require 'test_helper'

1530
class ProductTest < ActiveJob::TestCase
1531 1532 1533 1534 1535 1536 1537
  test 'billing job scheduling' do
    assert_enqueued_with(job: BillingJob) do
      product.charge(account)
    end
  end
end
```
G
Gaurish Sharma 已提交
1538

1539 1540 1541 1542
Additional Testing Resources
----------------------------

### Testing Time-Dependent Code
G
Gaurish Sharma 已提交
1543

J
Jon Moss 已提交
1544
Rails provides built-in helper methods that enable you to assert that your time-sensitive code works as expected.
G
Gaurish Sharma 已提交
1545

V
Vijay Dev 已提交
1546
Here is an example using the [`travel_to`](http://api.rubyonrails.org/classes/ActiveSupport/Testing/TimeHelpers.html#method-i-travel_to) helper:
G
Gaurish Sharma 已提交
1547 1548

```ruby
V
Vijay Dev 已提交
1549
# Lets say that a user is eligible for gifting a month after they register.
G
Gaurish Sharma 已提交
1550
user = User.create(name: 'Gaurish', activation_date: Date.new(2004, 10, 24))
V
Vijay Dev 已提交
1551
assert_not user.applicable_for_gifting?
G
Gaurish Sharma 已提交
1552
travel_to Date.new(2004, 11, 24) do
S
Shia 已提交
1553
  assert_equal Date.new(2004, 10, 24), user.activation_date # inside the `travel_to` block `Date.current` is mocked
V
Vijay Dev 已提交
1554
  assert user.applicable_for_gifting?
G
Gaurish Sharma 已提交
1555
end
V
Vijay Dev 已提交
1556
assert_equal Date.new(2004, 10, 24), user.activation_date # The change was visible only inside the `travel_to` block.
G
Gaurish Sharma 已提交
1557 1558
```

Y
yuuji.yaginuma 已提交
1559
Please see [`ActiveSupport::Testing::TimeHelpers` API Documentation](http://api.rubyonrails.org/classes/ActiveSupport/Testing/TimeHelpers.html)
G
Gaurish Sharma 已提交
1560
for in-depth information about the available time helpers.