testing.md 51.4 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 11 12
* Rails testing terminology.
* How to write unit, functional, and integration tests for your application.
* Other popular testing approaches and plugins.
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33

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

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

Testing support was woven into the Rails fabric from the beginning. It wasn't an "oh! let's bolt on support for running tests because they're new and cool" epiphany. Just about every Rails application interacts heavily with a database and, as a result, your tests will need a database to interact with as well. To write efficient tests, you'll need to understand how to set up this database and populate it with sample data.

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

34 35 36
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.

Also, 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`.
37 38 39

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

Z
Zachary Scott 已提交
40
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:
41 42 43

```bash
$ ls -F test
P
Prem Sichanugrist 已提交
44 45
controllers/    helpers/        mailers/        test_helper.rb
fixtures/       integration/    models/
46 47
```

J
Jon Atack 已提交
48
The `models` directory is meant to hold tests for your models, the `controllers` directory is meant to hold tests for your controllers and the `integration` directory is meant to hold tests that involve any number of controllers interacting. There is also a directory for testing your mailers and one for testing view helpers.
49

Z
Zachary Scott 已提交
50
Fixtures are a way of organizing test data; they reside in the `fixtures` directory.
51 52 53 54 55

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

### The Low-Down on Fixtures

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

#### What Are Fixtures?

62
_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.
63

64
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.
65 66 67

#### YAML

Z
Zachary Scott 已提交
68
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`).
69 70 71 72

Here's a sample YAML fixture file:

```yaml
73
# lo & behold! I am a YAML comment!
74
david:
75 76 77
  name: David Heinemeier Hansson
  birthday: 1979-10-15
  profession: Systems development
78 79

steve:
80 81 82
  name: Steve Ross Kellock
  birthday: 1974-09-27
  profession: guy with keyboard
83 84
```

85
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.
86

87 88
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
89
a `belongs_to`/`has_many` association:
90 91 92 93 94 95 96 97 98 99 100 101 102

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

# In fixtures/articles.yml
one:
  title: Welcome to Rails!
  body: Hello world!
  category: about
```

103 104
Notice the `category` key of the `one` article found in `fixtures/articles.yml` has a value of `about`. This tells Rails to load the category `about` found in `fixtures/categories.yml`.

105
NOTE: For associations to reference one another by name, you cannot specify 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).
106

107 108 109 110 111 112 113
#### 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 %>:
J
Jonathan Roes 已提交
114 115
  username: <%= "user#{n}" %>
  email: <%= "user#{n}@example.com" %>
116 117 118 119 120
<% end %>
```

#### Fixtures in Action

Z
Zachary Scott 已提交
121
Rails by default automatically loads all fixtures from the `test/fixtures` directory for your models and controllers test. Loading involves three steps:
122

123 124 125
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
126

127
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))
128

S
Steve Klabnik 已提交
129
#### Fixtures are Active Record objects
130

J
Jon Atack 已提交
131
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:
132 133 134 135 136 137 138 139 140

```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
S
Sean Collins 已提交
141
email(david.partner.email, david.location_tonight)
142 143
```

144 145 146 147 148 149 150
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)
```

151 152 153
### Console Tasks for Running your Tests

Rails comes with a CLI command to run tests.
154
Here are some examples of how to use it:
155 156 157 158 159 160 161

```bash
$ bin/rails test # run all tests in the `test` directory
$ bin/rails test test/controllers # run all tests from specific directory
$ bin/rails test test/models/post_test.rb # run specific test
$ bin/rails test test/models/post_test.rb:44 # run specific test and line
```
162 163 164

We will cover each of types Rails tests listed above in this guide.

K
Kir Shatrov 已提交
165
Model Testing
166 167
------------------------

168
For this guide we will be using the application we built in the [Getting Started with Rails](getting_started.html) guide.
169

170
If you remember when you used the `rails generate scaffold` command from earlier. We created our first resource among other things it created a test stub in the `test/models` directory:
171 172

```bash
173
$ bin/rails generate scaffold article title:string body:text
174
...
175 176 177
create  app/models/article.rb
create  test/models/article_test.rb
create  test/fixtures/articles.yml
178 179 180
...
```

181 182 183 184 185 186 187 188
You can also generate the test stub for a model using the following command:

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

189
The default test stub in `test/models/article_test.rb` looks like this:
190 191 192 193

```ruby
require 'test_helper'

194
class ArticleTest < ActiveSupport::TestCase
P
Prem Sichanugrist 已提交
195 196 197
  # test "the truth" do
  #   assert true
  # end
198 199 200 201 202 203 204 205 206
end
```

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

```ruby
require 'test_helper'
```

207
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 your tests.
208 209

```ruby
210
class ArticleTest < ActiveSupport::TestCase
211 212
```

213
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, you'll see some of the methods it gives you.
214

215
Any method defined within a class inherited from `Minitest::Test`
216
(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.
217

218
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:
219 220 221 222 223 224 225

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

226
Which is approximately the same as writing this:
227 228 229 230 231 232 233

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

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

236 237 238
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:
239 240 241 242 243

```ruby
assert true
```

244
An assertion is a line of code that evaluates an object (or expression) for expected results. For example, an assertion can check:
245 246 247 248 249 250

* 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?

251
Every test must contain at least one assertion, with no restriction as to how many assertions are allowed. Only when all the assertions are successful will the test pass.
252

253
### Maintaining the test database schema
254

255 256 257 258 259 260 261 262
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
migrations. If so, it will try to load your `db/schema.rb` or `db/structure.sql`
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
the migrations against the development database (`bin/rake db:migrate`) will
bring the schema up to date.

263 264
NOTE: If existing migrations required modifications, the test database needs to
be rebuilt. This can be done by executing `bin/rake db:test:prepare`.
265 266 267

### Running Tests

268
Running a test is as simple as invoking the file containing the test cases through `rails test` command.
269 270

```bash
271
$ bin/rails test test/models/article_test.rb
272 273
.

P
Prem Sichanugrist 已提交
274
Finished tests in 0.009262s, 107.9680 tests/s, 107.9680 assertions/s.
275

P
Prem Sichanugrist 已提交
276 277
1 tests, 1 assertions, 0 failures, 0 errors, 0 skips
```
278

279 280
This will run all test methods from the test case.

A
Aaron Patterson 已提交
281
You can also run a particular test method from the test case by running the test and providing the `test method name`.
282 283

```bash
284
$ bin/rails test test/models/article_test.rb test_the_truth
285 286
.

P
Prem Sichanugrist 已提交
287 288 289
Finished tests in 0.009064s, 110.3266 tests/s, 110.3266 assertions/s.

1 tests, 1 assertions, 0 failures, 0 errors, 0 skips
290 291 292 293
```

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.

294 295
#### Your first failing test

296
To see how a test failure is reported, you can add a failing test to the `article_test.rb` test case.
297 298

```ruby
299 300 301
test "should not save article without title" do
  article = Article.new
  assert_not article.save
302 303 304
end
```

305
Let us run this newly added test (where `6` is the number of line where the test is defined).
306 307

```bash
308
$ bin/rails test test/models/article_test.rb:6
309
F
P
Prem Sichanugrist 已提交
310 311

Finished tests in 0.044632s, 22.4054 tests/s, 22.4054 assertions/s.
312 313

  1) Failure:
314
test_should_not_save_article_without_title(ArticleTest) [test/models/article_test.rb:6]:
P
Prem Sichanugrist 已提交
315
Failed assertion, no message given.
316

P
Prem Sichanugrist 已提交
317
1 tests, 1 assertions, 1 failures, 0 errors, 0 skips
318 319 320 321 322
```

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
323 324 325
test "should not save article without title" do
  article = Article.new
  assert_not article.save, "Saved the article without a title"
326 327 328 329 330 331 332
end
```

Running this test shows the friendlier assertion message:

```bash
  1) Failure:
333 334
test_should_not_save_article_without_title(ArticleTest) [test/models/article_test.rb:6]:
Saved the article without a title
335 336 337 338 339
```

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

```ruby
340
class Article < ActiveRecord::Base
341
  validates :title, presence: true
342 343 344 345 346 347
end
```

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

```bash
348
$ bin/rails test test/models/article_test.rb:6
349 350
.

P
Prem Sichanugrist 已提交
351 352 353
Finished tests in 0.047721s, 20.9551 tests/s, 20.9551 assertions/s.

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

356 357 358 359 360
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).
361

362 363
#### What an error looks like

364 365 366 367 368 369 370 371 372 373 374 375 376
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
377
$ bin/rails test test/models/article_test.rb
378
E
P
Prem Sichanugrist 已提交
379 380

Finished tests in 0.030974s, 32.2851 tests/s, 0.0000 assertions/s.
381 382

  1) Error:
383 384 385
test_should_report_error(ArticleTest):
NameError: undefined local variable or method `some_undefined_variable' for #<ArticleTest:0x007fe32e24afe0>
    test/models/article_test.rb:10:in `block in <class:ArticleTest>'
386

P
Prem Sichanugrist 已提交
387
1 tests, 0 assertions, 0 failures, 1 errors, 0 skips
388 389 390 391
```

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

392 393 394
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
395
[`config.active_support.test_order` option](configuring.html#configuring-active-support)
396
can be used to configure test order.
397

398 399
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
C
Calvin Tam 已提交
400
application. This eliminates the framework noise and helps to focus on your
401
code. However there are situations when you want to see the full
402
backtrace. Simply set the `-b` (or `--backtrace`) argument to enable this behavior:
403 404

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

408 409 410 411 412 413 414 415 416 417 418 419 420
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.

421
### Available Assertions
422 423 424

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.

425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
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
specify to make your test failure messages clearer. It's not required.

| 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`.|
A
Alexey Markov 已提交
446 447
| `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.|
448 449 450 451 452
| `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_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 an instance of `class`.|
| `assert_not_instance_of( class, obj, [msg] )`                    | Ensures that `obj` is not an instance of `class`.|
453
| `assert_kind_of( class, obj, [msg] )`                            | Ensures that `obj` is an instance of `class` or is descending from it.|
454 455 456 457 458 459 460 461 462 463 464 465 466 467
| `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?`|
| `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.|

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
[`Minitest::Assertions`](http://docs.seattlerb.org/minitest/Minitest/Assertions.html)
468

469 470 471 472 473 474
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

475
Rails adds some custom assertions of its own to the `minitest` framework:
476 477 478 479

| Assertion                                                                         | Purpose |
| --------------------------------------------------------------------------------- | ------- |
| `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.|
480
| `assert_no_difference(expressions, message = nil, &block)`                        | Asserts that the numeric result of evaluating an expression is not changed before and after invoking the passed in block.|
481 482
| `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.|
483
| `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. 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.|
484
| `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. You can also pass named routes such as `assert_redirected_to root_path` and Active Record objects such as `assert_redirected_to @article`.|
485 486 487

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

488 489 490 491 492 493 494 495 496
### A Brief Note About Minitest

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:

* `ActiveSupport::TestCase`
* `ActionController::TestCase`
* `ActionMailer::TestCase`
* `ActionView::TestCase`
* `ActionDispatch::IntegrationTest`
497
* `ActiveJob::TestCase`
498 499 500

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

501
NOTE: For more information on `Minitest`, refer to [Minitest](http://docs.seattlerb.org/minitest)
502

503 504 505
Functional Tests for Your Controllers
-------------------------------------

506
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're testing how your actions handle the requests and the expected result, or response in some cases an HTML view.
507 508 509 510 511 512 513 514 515 516 517

### What to Include in your Functional Tests

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?

518
Now that we have used Rails scaffold generator for our `Article` resource, it has already created the controller code and tests. You can take look at the file `articles_controller_test.rb` in the `test/controllers` directory.
519

520 521 522 523 524 525 526 527
The following command will generate a controller test case with a filled up
test for each of the seven default actions.

```bash
$ bin/rails generate test_unit:scaffold article
create test/controllers/articles_controller_test.rb
```

528
Let me take you through one such test, `test_should_get_index` from the file `articles_controller_test.rb`.
529 530

```ruby
531
# articles_controller_test.rb
532
class ArticlesControllerTest < ActionController::TestCase
533
  def test_should_get_index
534 535
    get :index
    assert_response :success
536
    assert_includes @response.body, 'Articles'
537
  end
538 539 540
end
```

541 542
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.
543 544 545

The `get` method kicks off the web request and populates the results into the response. It accepts 4 arguments:

546 547 548
* The action of the controller you are requesting.
  This can be in the form of a string or a symbol.

549
* `params`: option with a hash of request parameters to pass into the action
550 551
  (e.g. query string parameters or article variables).

552
* `session`: option with a hash of session variables to pass along with the request.
553

554
* `flash`: option with a hash of flash values.
555 556

All the keyword arguments are optional.
557 558 559 560

Example: Calling the `:show` action, passing an `id` of 12 as the `params` and setting a `user_id` of 5 in the session:

```ruby
561
get(:show, params: { id: 12 }, session: { user_id: 5 })
562 563 564 565 566
```

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
567
get(:view, params: { id: 12 }, flash: { message: 'booya!' })
568 569
```

570
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.
571

572
Let us modify `test_should_create_article` test in `articles_controller_test.rb` so that all our test pass:
573 574

```ruby
575
def test_should_create_article
576
  assert_difference('Article.count') do
577
    post :create, params: { article: { title: 'Some title' } }
578 579
  end

580
  assert_redirected_to article_path(Article.last)
581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
end
```

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:

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

597
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.
598

599
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.
600

K
Kir Shatrov 已提交
601 602
### Testing XHR (AJAX) requests

603 604
To test AJAX requests, you can specify the `xhr: true` option to `get`, `post`,
`patch`, `put`, and `delete` methods:
K
Kir Shatrov 已提交
605 606

```ruby
607
test "ajax request" do
608
  get :show, params: { id: articles(:first).id }, xhr: true
K
Kir Shatrov 已提交
609

610 611
  assert_equal 'hello world', @response.body
  assert_equal "text/javascript", @response.content_type
K
Kir Shatrov 已提交
612 613 614
end
```

A
Alexey Markov 已提交
615
### The Three Hashes of the Apocalypse
616

A
Alexey Markov 已提交
617
After a request has been made and processed, you will have 3 Hash objects ready for use:
618 619 620 621 622

* `cookies` - Any cookies that are set.
* `flash` - Any objects living in the flash.
* `session` - Any object living in session variables.

623
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:
624 625 626 627 628 629 630 631 632 633 634 635

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

### Instance Variables Available

You also have access to three instance variables in your functional tests:

* `@controller` - The controller processing the request
636 637
* `@request` - The request object
* `@response` - The response object
638

639 640
### Setting Headers and CGI variables

641 642 643 644
[HTTP headers](http://tools.ietf.org/search/rfc2616#section-5.3)
and
[CGI variables](http://tools.ietf.org/search/rfc3875#section-4.1)
can be set directly on the `@request` instance variable:
645 646 647

```ruby
# setting a HTTP Header
648
@request.headers["Accept"] = "text/plain, text/html"
649 650 651 652 653 654 655
get :index # simulate the request with custom header

# setting a CGI variable
@request.headers["HTTP_REFERER"] = "http://example.com/home"
post :create # simulate the request with custom env variable
```

656
### Testing `flash` notices
657

A
Alexey Markov 已提交
658
If you remember from earlier one of the Three Hashes of the Apocalypse was `flash`.
659 660 661 662 663

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:
664 665

```ruby
A
Alexey Markov 已提交
666
test_should_create_article do
R
Robin Dupret 已提交
667
  assert_difference('Article.count') do
668
    post :create, params: { article: { title: 'Some title' } }
669
  end
670

671
  assert_redirected_to article_path(Article.last)
672
  assert_equal 'Article was successfully created.', flash[:notice]
673 674 675
end
```

676 677 678
If we run our test now, we should see a failure:

```bash
679
$ bin/rails test test/controllers/articles_controller_test.rb test_should_create_article
680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716
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:
ArticlesControllerTest#test_should_create_article [/Users/zzak/code/bench/sharedapp/test/controllers/articles_controller_test.rb:16]:
--- 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
717
$ bin/rails test test/controllers/articles_controller_test.rb test_should_create_article
718 719 720 721 722 723 724 725 726 727 728
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
```

729 730 731 732 733 734 735 736 737
### 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)
738
  get :show, params: { id: article.id }
739 740 741 742 743 744 745 746 747 748 749 750
  assert_response :success
end
```

Remember from our discussion earlier on fixtures the `articles()` method will give us access to our Articles fixtures.

How about deleting an existing Article?

```ruby
test "should destroy article" do
  article = articles(:one)
  assert_difference('Article.count', -1) do
751
    delete :destroy, params: { id: article.id }
752 753 754 755 756 757 758 759 760 761 762
  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)
763
  patch :update, params: { id: article.id, article: { title: "updated" } }
764
  assert_redirected_to article_path(article)
765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782
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`.

Our test should now look something like this, disregard the other tests we're leaving them out for brevity.

```ruby
require 'test_helper'

class ArticlesControllerTest < ActionController::TestCase
  # called before every single test
  def setup
    @article = articles(:one)
  end

  # called after every single test
  def teardown
783 784
    # when controller is using cache it may be a good idea to reset it afterwards
    Rails.cache.clear
785 786 787 788
  end

  test "should show article" do
    # Reuse the @article instance variable from setup
789
    get :show, params: { id: @article.id }
790 791 792 793 794
    assert_response :success
  end

  test "should destroy article" do
    assert_difference('Article.count', -1) do
795
      delete :destroy, params: { id: @article.id }
796 797 798 799 800 801
    end

    assert_redirected_to articles_path
  end

  test "should update article" do
802
    patch :update, params: { id: @article.id, article: { title: "updated" } }
803
    assert_redirected_to article_path(@article)
804 805 806 807 808 809
  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 已提交
810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843
### Test helpers

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

```ruby
test/test_helper.rb

module SignInHelper
  def sign_in(user)
    session[:user_id] = user.id
  end
end

class ActionController::TestCase
  include SignInHelper
end
```

```ruby
require 'test_helper'

class ProfileControllerTest < ActionController::TestCase

  test "should show profile" do
    # helper is now reusable from any controller test case
    sign_in users(:david)

    get :show
    assert_response :success
  end
end
```

844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860
Testing Routes
--------------

Like everything else in your Rails application, it is recommended that you test your routes. Below are example tests for the routes of default `show` and `create` action of `Articles` controller above and it should look like:

```ruby
class ArticleRoutesTest < ActionController::TestCase
  test "should route to article" do
    assert_routing '/articles/1', { controller: "articles", action: "show", id: "1" }
  end

  test "should route to create article" do
    assert_routing({ method: 'post', path: '/articles' }, { controller: "articles", action: "create" })
  end
end
```

861 862 863
I've added this file here `test/controllers/articles_routes_test.rb` and if we run the test we should see:

```bash
864
$ bin/rails test test/controllers/articles_routes_test.rb
865 866 867 868 869 870 871 872 873 874 875 876

# Running:

..

Finished in 0.069381s, 28.8263 runs/s, 86.4790 assertions/s.

2 runs, 6 assertions, 0 failures, 0 errors, 0 skips
```

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

877 878
Testing Views
-------------
879

B
Benjamin Klotz 已提交
880
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.
881 882 883

There are two forms of `assert_select`:

884
`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.
885

886
`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.
887 888 889 890 891 892 893

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

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

894 895 896 897
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:
898 899 900 901 902 903 904

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

905 906 907
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.
908 909 910 911 912 913 914 915 916 917 918 919 920

```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
```

921
This assertion is quite powerful. For more advanced usage, refer to its [documentation](http://www.rubydoc.info/github/rails/rails-dom-testing).
922 923 924 925 926

#### Additional View-Based Assertions

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

S
Sunny Ripert 已提交
927 928 929 930 931
| 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.|
932 933 934 935 936 937 938 939 940

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 已提交
941
Testing Helpers
942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973
---------------

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.

A helper test looks like so:

```ruby
require 'test_helper'

class UserHelperTest < ActionView::TestCase
end
```

A helper is just a simple module where you can define methods which are
available into your views. To test the output of the helper's methods, you just
have to use a mixin like this:

```ruby
class UserHelperTest < ActionView::TestCase
  include UserHelper

  test "should return the user name" do
    # ...
  end
end
```

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

974 975 976
Integration Testing
-------------------

977
Integration tests are used to test how various parts of your application interact. They are generally used to test important work flows within your application.
978

979
For creating Rails integration tests, we use the 'test/integration' directory for your application. Rails provides a generator to create an integration test skeleton for you.
980 981

```bash
982
$ bin/rails generate integration_test user_flows
983 984 985 986 987 988 989 990 991 992
      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
P
Prem Sichanugrist 已提交
993 994 995
  # test "the truth" do
  #   assert true
  # end
996 997 998
end
```

999
Inheriting from `ActionDispatch::IntegrationTest` comes with some advantages. This makes available some additional helpers to use in your integration tests.
1000 1001 1002

### Helpers Available for Integration Tests

1003 1004 1005 1006 1007 1008 1009
In addition to the standard testing helpers, inheriting `ActionDispatch::IntegrationTest` comes with some additional helpers available when writing integration tests. Let's briefly introduce you to the three categories of helpers you get to choose from.

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

When performing requests, you will have [`ActionDispatch::Integration::RequestHelpers`](http://api.rubyonrails.org/classes/ActionDispatch/Integration/RequestHelpers.html) available for your use.

If you'd like to modify the session, or state of your integration test you should look for [`ActionDispatch::Integration::Session`](http://api.rubyonrails.org/classes/ActionDispatch/Integration/Session.html) to help.
1010

1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053
### 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
```

It should have created a test file placeholder for us, with the output of the previous command you should see:

```bash
      invoke  test_unit
      create    test/integration/blog_flow_test.rb
```

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

```ruby
require 'test_helper'

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

If you remember from earlier in the "Testing Views" section we covered `assert_select` to query the resulting HTML of a request.

When visit our root path, we should see `welcome/index.html.erb` rendered for the view. So this assertion should pass.

#### Creating articles integration

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

```ruby
test "can create an article" do
  get "/articles/new"
  assert_response :success

1054
  post "/articles",
1055
    params: { article: { title: "can create", body: "article successfully." } }
1056 1057 1058 1059 1060 1061 1062 1063 1064
  assert_response :redirect
  follow_redirect!
  assert_response :success
  assert_select "p", "Title:\n  can create"
end
```

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

A
Alexey Markov 已提交
1065
We start by calling the `:new` action on our Articles controller. This response should be successful.
1066 1067 1068 1069

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

```ruby
1070
post "/articles",
1071
  params: { article: { title: "can create", body: "article successfully." } }
1072 1073 1074 1075 1076 1077 1078 1079
assert_response :redirect
follow_redirect!
```

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

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

A
Alexey Markov 已提交
1080
Finally we can assert that our response was successful and our new article is readable on the page.
1081 1082 1083

#### Taking it further

D
Dave Powers 已提交
1084
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.
1085

1086 1087 1088 1089 1090 1091 1092
Testing Your Mailers
--------------------

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

### Keeping the Postman in Check

1093
Your mailer classes - like every other part of your Rails application - should be tested to ensure that they are working as expected.
1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123

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.

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.

```ruby
require 'test_helper'

class UserMailerTest < ActionMailer::TestCase
  test "invite" do
1124
    # Send the email, then test that it got queued
1125 1126 1127 1128
    assert_emails 1 do
      email = UserMailer.create_invite('me@example.com',
                                       'friend@example.com', Time.now).deliver_now
    end
1129 1130 1131 1132 1133 1134

    # 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
1135 1136 1137 1138
  end
end
```

1139 1140 1141 1142
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.
1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153

Here's the content of the `invite` fixture:

```
Hi friend@example.com,

You have been invited.

Cheers!
```

1154 1155 1156 1157 1158 1159
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`).
1160

1161 1162 1163 1164
NOTE: The `ActionMailer::Base.deliveries` array is only reset automatically in
`ActionMailer::TestCase` tests. If you want to have a clean slate outside Action
Mailer tests, you can reset it manually with:
`ActionMailer::Base.deliveries.clear`
1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175

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

class UserControllerTest < ActionController::TestCase
  test "invite friend" do
    assert_difference 'ActionMailer::Base.deliveries.size', +1 do
1176
      post :invite_friend, params: { email: 'friend@example.com' }
1177 1178 1179 1180 1181
    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]
1182
    assert_match(/Hi friend@example.com/, invite_email.body.to_s)
1183 1184 1185 1186
  end
end
```

1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219
Testing Jobs
------------

Since your custom jobs can be queued at different levels inside your application,
you'll need to test both jobs themselves (their behavior when they get enqueued)
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.

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

1220
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).
1221 1222 1223 1224 1225 1226 1227 1228 1229

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'

1230
class ProductTest < ActiveJob::TestCase
1231 1232 1233 1234 1235 1236 1237 1238
  test 'billing job scheduling' do
    assert_enqueued_with(job: BillingJob) do
      product.charge(account)
    end
  end
end
```

1239 1240 1241
Other Testing Approaches
------------------------

1242
The built-in `minitest` 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:
1243 1244 1245

* [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.
1246
* [Fixture Builder](https://github.com/rdy/fixture_builder), a tool that compiles Ruby factories into fixtures before a test run.
1247
* [MiniTest::Spec Rails](https://github.com/metaskills/minitest-spec-rails), use the MiniTest::Spec DSL within your rails tests.
1248 1249
* [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
1250
* [Capybara](http://jnicklas.github.com/capybara/), Acceptance test framework for web applications