Veja mais em rubyonrails.org: Mais Ruby on Rails

Testando Applicações Rails

Este guia cobre mecanismos nativos do Rails para testar suas aplicações.

Após ler este guia, você saberá:

1 Por que escrever testes para a sua aplicação Rails?

O Rails torna super fácil escrever seus testes. Ele começa produzindo um esqueleto de código de teste enquanto você cria seus models e controllers.

Ao rodar seus testes no Rails você pode garantir que seu código continua com a funcionalidade desejada mesmo após algumas grandes refatorações no código.

Os testes no Rails podem simular requisições no browser e com isso, você pode testar a resposta da sua aplicação sem ter que testar utilizando de fato seu o browser.

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

2.1 Rails Sets up for Testing from the Word Go

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:

$ ls -F test
application_system_test_case.rb  controllers/                     helpers/                         mailers/                         system/
channels/                        fixtures/                        integration/                     models/                          test_helper.rb

The helpers, mailers, and models directories are meant to hold tests for view helpers, mailers, and models, respectively. The channels directory is meant to hold tests for Action Cable connection and channels. 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.

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. System tests inherit from Capybara and perform in browser tests for your application.

Fixtures are a way of organizing test data; they reside in the fixtures directory.

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

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

The application_system_test_case.rb holds the default configuration for your system tests.

2.2 The Test Environment

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

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.

Your tests are run under RAILS_ENV=test.

2.3 Rails meets Minitest

If you remember, we used the bin/rails generate model command in the Getting Started with Rails guide. We created our first model, and among other things it created test stubs in the test directory:

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

The default test stub in test/models/article_test.rb looks like this:

require "test_helper"

class ArticleTest < ActiveSupport::TestCase
  # test "the truth" do
  #   assert true
  # end

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

require "test_helper"

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.

class ArticleTest < ActiveSupport::TestCase

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.

Any method defined within a class inherited from Minitest::Test (which is the superclass of ActiveSupport::TestCase) that begins with test_ 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.

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:

test "the truth" do
  assert true

Which is approximately the same as writing this:

def test_the_truth
  assert true

Although you can still use regular method definitions, using the test macro allows for a more readable test name.

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:

assert true

An assertion is a line of code that evaluates an object (or expression) for expected results. For example, an assertion can check:

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

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.

2.3.1 Your first failing test

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

test "should not save article without title" do
  article = Article.new
  assert_not article.save

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

$ bin/rails test test/models/article_test.rb:6
Run options: --seed 44656

# Running:


ArticleTest#test_should_not_save_article_without_title [/path/to/blog/test/models/article_test.rb:6]:
Expected true to be nil or false

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

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:

test "should not save article without title" do
  article = Article.new
  assert_not article.save, "Saved the article without a title"

Running this test shows the friendlier assertion message:

ArticleTest#test_should_not_save_article_without_title [/path/to/blog/test/models/article_test.rb:6]:
Saved the article without a title

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

class Article < ApplicationRecord
  validates :title, presence: true

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

$ bin/rails test test/models/article_test.rb:6
Run options: --seed 31252

# Running:


Finished in 0.027476s, 36.3952 runs/s, 36.3952 assertions/s.

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

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

2.3.2 What an Error Looks Like

To see how an error gets reported, here's a test containing an error:

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

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

$ bin/rails test test/models/article_test.rb
Run options: --seed 1808

# Running:


NameError: undefined local variable or method 'some_undefined_variable' for #<ArticleTest:0x007fee3aa71798>
    test/models/article_test.rb:11:in 'block in <class:ArticleTest>'

rails test test/models/article_test.rb:9

Finished in 0.040609s, 49.2500 runs/s, 24.6250 assertions/s.

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

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

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 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. Set the -b (or --backtrace) argument to enable this behavior:

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

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

This test should now pass.

2.4 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, 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.

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_in_epsilon ( expected, actual, [epsilon], [msg] ) Ensures that the numbers expected and actual have a relative error less than epsilon.
assert_not_in_epsilon ( expected, actual, [epsilon], [msg] ) Ensures that the numbers expected and actual have a relative error not less than epsilon.
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, specifically Minitest::Assertions.

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.

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

2.5 Rails Specific Assertions

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

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.
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.
assert_changes(expressions, message = nil, from:, to:, &block) Test that the result of evaluating an expression is changed after invoking the passed in block.
assert_no_changes(expressions, message = nil, &block) Test the result of evaluating an expression is not changed after invoking the passed in block.
assert_nothing_raised { block } Ensures that the given block doesn't raise any exceptions.
assert_recognizes(expected_options, path, extras={}, message=nil) Asserts that the routing of the given path was handled correctly and that the parsed options (given in the expected_options hash) match path. Basically, it asserts that Rails recognizes the route given by expected_options.
assert_generates(expected_path, options, defaults={}, extras = {}, message=nil) Asserts that the provided options can be used to generate the provided path. This is the inverse of assert_recognizes. The extras parameter is used to tell the request the names and values of additional request parameters that would be in a query string. The message parameter allows you to specify a custom error message for assertion failures.
assert_response(type, message = nil) Asserts that the response comes with a specific status code. You can specify :success to indicate 200-299, :redirect to indicate 300-399, :missing to indicate 404, or :error to match the 500-599 range. You can also pass an explicit status number or its symbolic equivalent. For more information, see full list of status codes and how their mapping works.
assert_redirected_to(options = {}, message=nil) Asserts that the response is a redirect to a URL matching the given options. You can also pass named routes such as assert_redirected_to root_path and Active Record objects such as assert_redirected_to @article.

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

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

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

For more information on Minitest, refer to its documentation.

2.7 The Rails Test Runner

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

Or we can run a single test file by passing the bin/rails test command the filename containing the test cases.

$ bin/rails test test/models/article_test.rb
Run options: --seed 1559

# Running:


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

2 runs, 3 assertions, 0 failures, 0 errors, 0 skips

This will run all test methods from the test case.

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.

$ bin/rails test test/models/article_test.rb -n test_the_truth
Run options: -n test_the_truth --seed 43583

# Running:


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.

$ bin/rails test test/models/article_test.rb:6 # run specific test and line

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

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

The test runner also provides a lot of other features like failing fast, deferring test output at the end of the test run and so on. Check the documentation of the test runner as follows:

$ bin/rails test -h
Usage: 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.

minitest options:
    -h, --help                       Display this help.
        --no-plugins                 Bypass minitest plugin auto-loading (or set $MT_NO_PLUGINS).
    -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
    -w, --warnings                   Run with Ruby warnings enabled
    -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
    -p, --pride                      Pride. Show your testing pride!

3 Testes em Paralelo

Testes em paralelo permitem a paralelização da sua suíte de testes. Ao passo que fazer fork de processos é o método padrão, também é suportado o uso de threads. Rodar testes em paralelo reduz o tempo que leva para rodar sua suíte de testes inteira.

3.1 Testes em Paralelo com Processos

O método padrão de paralelização é fazer fork de processos utilizando o sistema DRb do Ruby. Os número de processos utilizados depende do número de workers fornecidos. O número padrão é a quantidade de núcleos de seu computador, mas pode ser mudado para a quantidade passada para o método parallelize.

Para habilitar a paralelização adicione o seguinte em seu arquivo test_helper.rb:

class ActiveSupport::TestCase
  parallelize(workers: 2)

O número de workers informado é o número de vezes que o processo sofrerá fork. Voce pode querer paralelizar sua suíte de testes local de maneira diferente de seu CI, por isso uma variável de ambiente está disponível para que seja possível mudar facilmente o número de workers que uma execução dos testes deve usar:

$ PARALLEL_WORKERS=15 bin/rails test

Quando testes são paralelizados, o Active Record automaticamente lida com a criação dos bancos de dados e do carregamento do esquema (schema) no banco de dados de cada processo. Os bancos de dados criados serão sufixados de acordo com a numeração do worker. Por exemplo, se há 2 workers, os testes criarão os bancos test-database-0 e test-database-1 respectivamente.

Se o número de workers passado for 1 ou menos, os processos não sofrerão fork e os testes não serão paralelizados. Além disso, o banco de original test-database será usado.

Dois hooks são disponibilizados, um que roda quando o processo sofre fork e outro quando o fork é encerrado. Isso pode ser útil se sua aplicação usa múltiplos bancos de dados ou executa outras atividades que dependem da quantidade de workers.

O método parallelize_setup é chamado logo após o fork do processo. O método parallelize_teardown é chamado no momento antes do processo ser finalizado.

class ActiveSupport::TestCase
  parallelize_setup do |worker|
    # configuração dos bancos de dados

  parallelize_teardown do |worker|
    # limpeza dos bancos de dados

  parallelize(workers: :number_of_processors)

Esses métodos não são necessários ou estão indisponíveis quando testes paralelos com threads são utilizados.

3.2 Testes em Paralelo com Threads

Se você preferir utilizar threads ou está utilizando JRuby, a opção de paralelizar com threads está disponível. O paralelizador com threads utiliza por baixo dos panos a classe Parallel::Executor do Minitest.

Para mudar o método de paralelização para utilizar threads ao invés de forks, escreva o seguinte em seu test_helper.rb:

class ActiveSupport::TestCase
  parallelize(workers: :number_of_processors, with: :threads)

Aplicações Rails geradas com JRuby ou TruffleRuby irão incluir automaticamente a opção with: :threads.

o número de workers passado para parallelize determina o número de threads que os testes irão utilizar. Voce pode querer paralelizar sua suíte de testes de maneira diferente de seu CI, por isso uma variável de ambiente está disponível para que seja possível mudar facilmente o número de workers que uma execução dos testes deve usar:

$ PARALLEL_WORKERS=15 bin/rails test

3.3 Testando Transações em Paralelo

O Rails automaticamente envolve todo caso de teste em uma transação do banco de dados, que é desfeita depois que o teste é concluído. Isso faz com que os casos de teste sejam independentes uns dos outros e faz com que as mudanças no banco de dados sejam visíveis somente dentro daquele teste.

Quando você testa código que roda transações paralelas em threads, as transações podem bloquear umas às outras, pois eles já estão aninhadas com a transação do caso de teste.

Você pode desabilitar transações na classe de um caso de teste, através da configuração self.use_transactional_tests = false:

class WorkerTest < ActiveSupport::TestCase
  self.use_transactional_tests = false

  test "parallel transactions" do
    # inicia threads que criam transações

Com os testes transacionais desligados, você terá que que limpar os dados de teste criados, já que a as mudanças não são automaticamente desfeitas depois que o teste termina.

4 O Banco de Dados de Teste

Quase tudo em uma aplicação Rails interage fortemente com um banco de dados e, como resultado, seus testes também precisarão interagir com um banco de dados. Para escrever testes eficientes, você precisará entender como configurar e como popular esse banco de dados com dados de exemplo.

Por padrão, toda aplicação Rails tem 3 ambientes (environments): development, test e production. O banco de dados de cada ambiente é configurado em config/database.yml.

Um banco de dados dedicado aos testes permite a configuração e a interação com os dados de teste separadamente. Dessa forma, seus testes podem manipular dados de teste com confiança, sem se preocupar com os bancos de desenvolvimento ou produção.

4.1 Mantendo o esquema do banco de dados de teste

Para rodar os testes, seu banco de dados precisará ter a estrutura atual. A classe test helper checa se seu banco de teste tem alguma migração pendente. Ela vai tentar carregar seu db/schema.rb ou db/structure.sql dentro do banco de teste. Se alguma migração ainda estiver faltando, um erro vai ser levantado. Isso indica que seu esquema (schema) ainda não foi totalmente migrado. Rodar as migrações do banco de desenvolvimento (bin/rails db:migrate) irá atualizar o esquema para a última versão.

Se migrações que já existiam forem modificadas, o banco de dados de teste precisará ser refeito. Isso pode ser feito executando bin/rails db:test:prepare.

4.2 O Essencial sobre Fixtures

Para fazer bons testes, você precisará pensar bastante em como irá preparar seus dados de teste. No Rails, você pode lidar com isso definindo e customizando fixtures. Você pode encontrar a documentação completa em documentação da API de Fixtures.

4.2.1 O que são Fixtures?

Fixtures é uma apenas uma palavra bonita pra dados de teste. Fixtures permitem você popular seu banco de teste com dados predefinidos antes dos testes rodarem. Fixtures funcionam independentemente do banco de dados e são escritas em YAML. Há um arquivo por model.

Fixtures não foram feitas para criar todos os objetos que seus testes precisam e são melhor gerenciadas quando usadas somente para dados padrão que podem ser usados em casos comuns.

Você encontrará fixtures dentro da pasta test/fixtures. Quando se roda bin/rails generate model para criar um model, o Rails automaticamente cria um esqueleto de fixture nessa pasta.

4.2.2 YAML

Fixtures escritas em YAML são um jeito amigável para humanos de escrever seus dados de teste. Esse tipo de fixture vai ter a extensão .yml (como em users.yml).

Segue um exemplo de fixture em arquivo YAML:

# Vejam e contemplem! Eu sou um comentário em YAML!
  name: David Heinemeier Hansson
  birthday: 1979-10-15
  profession: Systems development

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

Cada fixture recebe um nome, seguido de uma lista indentada de chaves/valores separados por dois pontos. Registros são separados uns dos outros por uma linha em branco. Você pode colocar comentários em uma arquivo fixture usando o caractere # na primeira coluna do texto.

Se você está trabalhando com associações, você pode definir referências entre duas fixtures diferentes. Aqui está um exemplo com uma associação belongs_to/has_many:

# fixtures/categories.yml
  name: About
# fixtures/articles.yml
  title: Welcome to Rails!
  body: Hello world!
  category: about

Veja que a chave de category do artigo first encontrado em fixtures/articles.yml tem o valor about. Isso diz ao Rails para carregar a categoria about encontrada em fixtures/categories.yml.

Para que associações façam referência umas as outras pelo nome, você pode usar o nome da fixture ao invés de especificar a chave id: nas fixtures associadas. O Rails vai dar automaticamente uma chave para que haja consistência entre execuções dos testes. Para mais informações sobre esse comportamento das associações, leia a página documentação da API de Fixtures.

4.2.3 ERBzando as Fixtures

A linguagem ERB permite que você coloque código Ruby dentro de templates. As fixtures em formato YAML são pré-processadas com ERB antes do Rails carregar as fixtures. Isso faz com que você possa usar Ruby para ajudar a gerar dados de teste. Por exemplo, o código a seguir vai gerar mil usuários:

<% 1000.times do |n| %>
user_<%= n %>:
  username: <%= "user#{n}" %>
  email: <%= "user#{n}@example.com" %>
<% end %>
4.2.4 Fixtures em Ação

O Rails automaticamente carrega todas as fixtures dentro do diretório test/fixtures por padrão. O carregamento envolve três passos:

  1. Remover qualquer dado existente da tabela que corresponde a fixture
  2. Carregar os dados da fixture na tabela
  3. Copiar os dados da fixture para dentro de um método caso você queira acessá-los diretamente

Para remover todos os dados existentes, o Rails tenta desabilitar os triggers de integridade referencial (como chaves estrangeiras e constraints). Se você estiver recebendo erros irritantes de permissão na hora de rodar os testes, garanta que o usuário do banco de dados tenha permissão para desabilitar esses triggers no ambiente de teste. (No PostgreSQL, somente superusuários podem desativar todos os triggers. Leia mais sobre as permissões do PostgreSQL aqui).

4.2.5 Fixtures são objetos do Active Record

Fixtures são instâncias de Active Record. Como mencionado no ponto #3 acima, você pode acessar o objeto diretamente, já que ele está automaticamente acessível como um método cujo escopo é local para cada teste. Por exemplo:

# isso retornará um objeto User para a fixture chamada david

# isso retornará a propriedade id de david

# também é possível acessar os métodos disponíveis dentro de User
david = users(:david)

Para acessar várias fixtures de uma vez, você pode passar uma lista de nomes de fixtures. Por exemplo:

# isso retornará uma array contendo as fixtures david e steve
users(:david, :steve)

5 Testando Models

Testes de model são usados para testar os vários models de sua aplicação.

Os testes de model do Rails estão localizados em test/models. O Rails disponibiliza um gerador (generator) para criar esqueletos de testes de model.

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

Testes de model não possuem uma superclasse como ActionMailer::TestCase. Ao invés disso, eles herdam de ActiveSupport::TestCase.

6 Fazendo Testes de Sistema

Testes de sistema permitem testar interações do usuário com sua aplicação, rodando os testes em um navegador web real ou headless. Testes de sistema usam Capybara por debaixo dos panos.

Para criar testes de sistema do Rails, utilize o caminho test/system da sua aplicação. O Rails também disponibiliza um generator para criar esqueletos de testes de sistema para você.

$ bin/rails generate system_test users
      invoke test_unit
      create test/system/users_test.rb

Aqui está como um teste de sistema recém gerado se parece:

require "application_system_test_case"

class UsersTest < ApplicationSystemTestCase
  # test "visiting the index" do
  #   visit users_url
  #   assert_selector "h1", text: "Users"
  # end

Por padrão, testes de sistema utilizam o driver Selenium, executando o navegador Chrome, em uma tela de tamanho 1400x1400. A próxima seção explica como mudar as configurações padrão.

6.1 Mudando as Configurações Padrão

O Rails faz com que mudar as configurações padrão de testes de sistema seja muito simples. Toda a preparação (setup) é abstraída, logo você pode focar mais em escrever testes.

Quando uma nova aplicação ou scaffold são gerados, o arquivo application_system_test_case.rb é criado na pasta de testes. É nele em que todas as configurações de seus testes de sistema devem estão.

Se você quiser mudar as configurações padrão, você pode mudar quem "dirige" (driver) os testes de sistema. Digamos que você quer mudar de Selenium para Poltergeist. Primeiro adicione a gem poltergeist em seu Gemfile. Depois, em seu application_system_test_case.rb, faça o seguinte:

require "test_helper"
require "capybara/poltergeist"

class ApplicationSystemTestCase < ActionDispatch::SystemTestCase
  driven_by :poltergeist

O nome do driver é um argumento obrigatório de driven_by. Os argumentos opcionais que podem ser passados para driven_by são :using para o navegador web (opção usada somente pelo driver Selenium), :screen_size para mudar o tamanho da tela e das capturas de tela e :options que serve para configurações específicas de cada driver.

require "test_helper"

class ApplicationSystemTestCase < ActionDispatch::SystemTestCase
  driven_by :selenium, using: :firefox

Se você quiser usar um navegador headless, você pode usar o Chrome headless ou Firefox headless passando headless_chrome ou headless_firefox para o argumento :using.

require "test_helper"

class ApplicationSystemTestCase < ActionDispatch::SystemTestCase
  driven_by :selenium, using: :headless_chrome

Se a sua configuração do Capybara requer mais customização do que as fornecidas pelo Rails, opções adicionais podem ser adicionadas no arquivo application_system_test_case.rb.

Consulte a documentação do Capybara para configurações adicionais.

6.2 Helper de capturas de tela

O módulo ScreenshotHelper é um helper feito para fazer capturas de tela ("prints") dos seus testes. Isso pode ser útil para ver o navegador web no momento em que um teste falha ou para debug.

Dois métodos são disponibilizados: take_screenshot e take_failed_screenshot. No Rails, o método take_failed_screenshot é automaticamente incluído em before_teardown.

O helper take_screenshot pode ser chamado em qualquer lugar nos seus testes para fazer uma captura de tela do navegador.

6.3 Implementando um Teste de Sistema

Agora vamos adicionar um teste de sistema em nossa aplicação de blog. Vamos demonstrar como escrever testes de sistema, através da visita a página inicial da aplicação e da escrita de um novo artigo de blog.

Se você tive usado o generator de scaffold, então o esqueleto de um teste de sistema foi automaticamente criado para você. Se você não utilizou o generator de scaffold, comece criando o esqueleto de um teste de sistema.

$ bin/rails generate system_test articles

Isso deveria criar um arquivo de teste. Se você utilizou o comando anterior, você deveria ver a seguinte saída:

      invoke  test_unit
      create    test/system/articles_test.rb

Agora vamos abrir o arquivo e escrever nossa primeira asserção:

require "application_system_test_case"

class ArticlesTest < ApplicationSystemTestCase
  test "viewing the index" do
    visit articles_path
    assert_selector "h1", text: "Articles"

O teste deveria localizar que há um elemento h1 na página inicial (index) de articles e passar.

Rode os testes de sistema.

$ bin/rails test:system

Por padrão, rodar bin/rails test não irá rodar seus testes de sistema. Certifique-se de rodar bin/rails test:system para que eles sejam executados. Você também pode executar bin/rails test:all para rodar todos os testes, incluindo os de sistema.

6.3.1 Criando um Teste de Sistema de Artigos

Agora vamos testar o fluxo de criação de um novo artigo para o nosso blog.

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"

O primeiro passo é chamar visit articles_path. Isso faz com que o teste acesse a página inicial (index) de articles.

Depois a instrução click_on "New Article" vai achar o botão "New Article" na página inicial (index). Isso vai redirecionar o navegador para /articles/new.

Após isso, o teste vai preencher o título (title) e o corpo (body) do artigo com o texto especificado. Uma vez que os campos estão preenchidos, clica-se em "Create Article", que irá mandar uma requisição POST para criar o artigo no banco de dados.

Finalmente, nós vamos ser redirecionados de volta para a página inicial (index) e lá vamos assertar que o texto do título de nosso novo artigo está presente na página inicial.

6.3.2 Testando em diferentes tamanhos de tela

Se você quiser testar em telas de tamanho mobile além do tamanho desktop, você pode criar outra classe que herda de SystemTestCase para usar em sua suite de testes. Nesse exemplo, um arquivo chamado mobile_system_test_case.rb foi criado no caminho /test com a seguinte configuração:

require "test_helper"

class MobileSystemTestCase < ActionDispatch::SystemTestCase
  driven_by :selenium, using: :chrome, screen_size: [375, 667]

Para usar essa configuração, crie um teste dentro de test/system que herda de MobileSystemTestCase. Agora você pode testar seu app com diferentes configurações de tela.

require "mobile_system_test_case"

class PostsTest < MobileSystemTestCase

  test "visiting the index" do
    visit posts_url
    assert_selector "h1", text: "Posts"
6.3.3 Indo Além

A beleza dos testes de sistema é que, parecido com os testes de integração, eles também testam a interação do usuário com o controller, model e a view. Porém, o teste de sistema é muito mais robusto e testa a aplicação como se uma pessoa de verdade estivesse usando. Indo além, você pode testar qualquer coisa que os próprios usuários fariam em sua aplicação, como comentar, deletar artigos, publicar rascunhos e etc.

7 Integration Testing

Integration tests are used to test how various parts of our application interact. They are generally used to test important workflows within our application.

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.

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

require "test_helper"

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

Here the test is inheriting from ActionDispatch::IntegrationTest. This makes some additional helpers available for us to use in our integration tests.

7.1 Helpers Available for Integration Tests

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.

For dealing with the integration test runner, see ActionDispatch::Integration::Runner.

When performing requests, we will have ActionDispatch::Integration::RequestHelpers available for our use.

If we need to modify the session, or state of our integration test, take a look at ActionDispatch::Integration::Session to help.

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

$ bin/rails generate integration_test blog_flow

It should have created a test file placeholder for us. With the output of the previous command we should see:

      invoke  test_unit
      create    test/integration/blog_flow_test.rb

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

require "test_helper"

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

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.

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

7.2.1 Creating articles integration

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

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

  post "/articles",
    params: { article: { title: "can create", body: "article successfully." } }
  assert_response :redirect
  assert_response :success
  assert_select "p", "Title:\n  can create"

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

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

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

post "/articles",
  params: { article: { title: "can create", body: "article successfully." } }
assert_response :redirect

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

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

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

7.2.2 Taking it further

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.

8 Functional Tests for Your Controllers

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.

8.1 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 appropriate message displayed to the user in the view?
  • was the correct information displayed in the response?

The easiest way to see functional tests in action is to generate a controller using the scaffold generator:

$ bin/rails generate scaffold_controller article title:string body:text
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. You can take a look at the file articles_controller_test.rb in the test/controllers directory.

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:

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

Let's take a look at one such test, test_should_get_index from the file articles_controller_test.rb.

# articles_controller_test.rb
class ArticlesControllerTest < ActionDispatch::IntegrationTest
  test "should get index" do
    get articles_url
    assert_response :success

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.

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

  • 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).
  • params: option with a hash of request parameters to pass into the action (e.g. query string parameters or article variables).
  • 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.

All of these keyword arguments are optional.

Example: Calling the :show action for the first Article, passing in an HTTP_REFERER header:

get article_url(Article.first), headers: { "HTTP_REFERER" => "http://example.com/home" }

Another example: Calling the :update action for the last Article, passing in new text for the title in params, as an Ajax request:

patch article_url(Article.last), params: { article: { title: "updated" } }, xhr: true

One more example: Calling the :create action to create a new article, passing in text for the title in params, as JSON request:

post articles_path, params: { article: { title: "Ahoy!" } }, as: :json

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.

Let us modify test_should_create_article test in articles_controller_test.rb so that all our test pass:

test "should create article" do
  assert_difference("Article.count") do
    post articles_url, params: { article: { body: "Rails is awesome!", title: "Hello Rails" } }

  assert_redirected_to article_path(Article.last)

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

If you followed the steps in the Basic Authentication section, you'll need to add authorization to every request header to get all the tests passing:

post articles_url, params: { article: { body: "Rails is awesome!", title: "Hello Rails" } }, headers: { Authorization: ActionController::HttpAuthentication::Basic.encode_credentials("dhh", "secret") }

8.2 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

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.

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.

8.3 Testing XHR (AJAX) requests

To test AJAX requests, you can specify the xhr: true option to get, post, patch, put, and delete methods. For example:

test "ajax request" do
  article = articles(:one)
  get article_url(article), xhr: true

  assert_equal "hello world", @response.body
  assert_equal "text/javascript", @response.media_type

8.4 The Three Hashes of the Apocalypse

After a request has been made and processed, you will have 3 Hash objects ready for use:

  • cookies - Any cookies that are set
  • flash - Any objects living in the flash
  • session - Any object living in session variables

As is the case with normal Hash objects, you can access the values by referencing the keys by string. You can also reference them by symbol name. For example:

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

8.5 Instance Variables Available

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

  • @controller - The controller processing the request
  • @request - The request object
  • @response - The response object
class ArticlesControllerTest < ActionDispatch::IntegrationTest
  test "should get index" do
    get articles_url

    assert_equal "index", @controller.action_name
    assert_equal "application/x-www-form-urlencoded", @request.media_type
    assert_match "Articles", @response.body

8.6 Setting Headers and CGI variables

HTTP headers and CGI variables can be passed as headers:

# setting an HTTP Header
get articles_url, headers: { "Content-Type": "text/plain" } # simulate the request with custom header

# setting a CGI variable
get articles_url, headers: { "HTTP_REFERER": "http://example.com/home" } # simulate the request with custom env variable

8.7 Testing flash notices

If you remember from earlier, one of the Three Hashes of the Apocalypse was flash.

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:

test "should create article" do
  assert_difference("Article.count") do
    post articles_url, params: { article: { title: "Some title" } }

  assert_redirected_to article_path(Article.last)
  assert_equal "Article was successfully created.", flash[:notice]

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

$ bin/rails test test/controllers/articles_controller_test.rb -n test_should_create_article
Run options: -n test_should_create_article --seed 32266

# Running:


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

  1) Failure:
ArticlesControllerTest#test_should_create_article [/test/controllers/articles_controller_test.rb:16]:
--- expected
+++ actual
@@ -1 +1 @@
-"Article was successfully created."

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:

def create
  @article = Article.new(article_params)

  if @article.save
    flash[:notice] = "Article was successfully created."
    redirect_to @article
    render "new"

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

$ bin/rails test test/controllers/articles_controller_test.rb -n test_should_create_article
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

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

test "should show article" do
  article = articles(:one)
  get article_url(article)
  assert_response :success

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

How about deleting an existing Article?

test "should destroy article" do
  article = articles(:one)
  assert_difference("Article.count", -1) do
    delete article_url(article)

  assert_redirected_to articles_path

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

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

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

  assert_redirected_to article_path(article)
  # Reload association to fetch updated data and assert that title is updated.
  assert_equal "updated", article.title

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 as what follows. Disregard the other tests for now, we're leaving them out for brevity.

require "test_helper"

class ArticlesControllerTest < ActionDispatch::IntegrationTest
  # called before every single test
  setup do
    @article = articles(:one)

  # called after every single test
  teardown do
    # when controller is using cache it may be a good idea to reset it afterwards

  test "should show article" do
    # Reuse the @article instance variable from setup
    get article_url(@article)
    assert_response :success

  test "should destroy article" do
    assert_difference("Article.count", -1) do
      delete article_url(@article)

    assert_redirected_to articles_path

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

    assert_redirected_to article_path(@article)
    # Reload association to fetch updated data and assert that title is updated.
    assert_equal "updated", @article.title

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.

8.9 Test helpers

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

# test/test_helper.rb

module SignInHelper
  def sign_in_as(user)
    post sign_in_url(email: user.email, password: user.password)

class ActionDispatch::IntegrationTest
  include SignInHelper
require "test_helper"

class ProfileControllerTest < ActionDispatch::IntegrationTest

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

    get profile_url
    assert_response :success
8.9.1 Using Separate Files

If you find your helpers are cluttering test_helper.rb, you can extract them into separate files. One good place to store them is test/lib or test/test_helpers.

# test/test_helpers/multiple_assertions.rb
module MultipleAssertions
  def assert_multiple_of_forty_two(number)
    assert (number % 42 == 0), 'expected #{number} to be a multiple of 42'

These helpers can then be explicitly required as needed and included as needed

require "test_helper"
require "test_helpers/multiple_assertions"

class NumberTest < ActiveSupport::TestCase
  include MultipleAssertions

  test "420 is a multiple of forty two" do
    assert_multiple_of_forty_two 420

or they can continue to be included directly into the relevant parent classes

# test/test_helper.rb
require "test_helpers/sign_in_helper"

class ActionDispatch::IntegrationTest
  include SignInHelper
8.9.2 Eagerly Requiring Helpers

You may find it convenient to eagerly require helpers in test_helper.rb so your test files have implicit access to them. This can be accomplished using globbing, as follows

# test/test_helper.rb
Dir[Rails.root.join("test", "test_helpers", "**", "*.rb")].each { |file| require file }

This has the downside of increasing the boot-up time, as opposed to manually requiring only the necessary files in your individual tests.

9 Testando Rotas

Assim como tudo na sua aplicação Rails, você também pode testar suas rotas. Testes de rotas são encontrados na pasta test/controllers/ ou podem fazer parte de seus testes de controller.

Se sua aplicação tem rotas muito complexas, o Rails fornece vários helpers úteis para testá-las.

Para mais informações sobre as asserções de rotas disponíveis no Rails, veja a documentação da API de ActionDispatch::Assertions::RoutingAssertions.

10 Testando Views

Testar a resposta de sua requisição através da presença de elementos HTML chave e o seu conteúdo é uma forma comum de testar as views de sua aplicação. Assim como os testes de rota, testes de view ficam em test/controllers/ ou são parte dos seus testes de controller.

O método assert_select permite que você faça consultas a elementos HTML da resposta, através de uma sintaxe simples, mas poderosa.

Há duas formas de assert_select:

A assinatura assert_select(selector, [equality], [message]) garante que a condição de igualdade (equality) é atendida nos elementos selecionados através do seletor (selector). O argumento selector pode ser um seletor CSS (String) ou uma expressão com valores de substituição (como nesses testes).

assert_select(element, selector, [equality], [message]) garante que a condição de igualdade (equality) é atendida nos elementos selecionados através do seletor, começando no elemento element (instância de Nokogiri::XML::Node ou Nokogiri::XML::NodeSet) e seus descendentes.

Por exemplo, você poderia verificar o conteúdo do elemento title na sua resposta com:

assert_select "title", "Welcome to Rails Testing Guide"

Você também pode usar blocos aninhados de assert_select para uma investigação mais profunda.

No exemplo a seguir, o assert_select mais interno de li.menu_item executa com a coleção de elementos selecionados pelo bloco mais externo:

assert_select "ul.navigation" do
  assert_select "li.menu_item"

Uma coleção de elementos pode ser iterada para que assert_select possa ser chamado individualmente para cada elemento.

Por exemplo, se a resposta contiver duas listas ordenadas, cada uma com quatro elementos, então os testes a seguir irão passar.

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

assert_select "ol" do
  assert_select "li", 8

Essa asserção é bastante poderosa. Para usos mais avançados, veja a sua documentação.

10.1 Asserções Adicionais para Views

Existem mais asserções que são usadas primariamente em testes de views:

Asserção Propósito
assert_select_email Permite fazer asserções no corpo de um email.
assert_select_encoded Permite fazer asserções em HTML codificado. Isso é feito decodificando os conteúdos de cada elemento e então chamando o bloco com todos os elementos decodificados.
css_select(selector) ou css_select(element, selector) Retorna uma array de todos os elementos selecionados por selector. Na segunda variante, o método primeiro seleciona o elemento base element e depois tenta selecionar os descendentes de element através de selector. Se não houver nenhum match, ambas variantes retornam array vazia.

Aqui está um exemplo do uso de assert_selected_email:

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

11 Testando os Helpers

Um helper é apenas um simples módulo onde você pode definir métodos que estarão disponíveis nas suas views.

Para testar os helpers, tudo que você precisa fazer é verificar se a saída do método helper é de fato a saída esperada. Testes relacionados aos helpers estão localizados dentro da pasta test/helpers.

Dado o seguinte helper:

module UsersHelper
  def link_to_user(user)
    link_to "#{user.first_name} #{user.last_name}", user

Nós podemos testar a saída desse método da seguinte maneira:

class UsersHelperTest < ActionView::TestCase
  test "should return the user's full name" do
    user = users(:david)

    assert_dom_equal %{<a href="/user/#{user.id}">David Heinemeier Hansson</a>}, link_to_user(user)

Além disso, uma vez que a classe de teste se estende de ActionView::TestCase, você tem acesso aos métodos auxiliares do Rails como link_to oupluralize.

12 Testing Your Mailers

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

12.1 Keeping the Postman in Check

Your mailer classes - like every other part of your Rails application - should be tested to ensure that they are working as expected.

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

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

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

If you generated your mailer, the generator does not create stub fixtures for the mailers actions. You'll have to create those files yourself as described above.

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

require "test_helper"

class UserMailerTest < ActionMailer::TestCase
  test "invite" do
    # Create the email and store it for further assertions
    email = UserMailer.create_invite("[email protected]",
                                     "[email protected]", Time.now)

    # Send the email, then test that it got queued
    assert_emails 1 do

    # Test the body of the sent email contains what we expect it to
    assert_equal ["[email protected]"], email.from
    assert_equal ["[email protected]"], email.to
    assert_equal "You have been invited by [email protected]", email.subject
    assert_equal read_fixture("invite").join, email.body.to_s

In the test we create 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.

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

Here's the content of the invite fixture:

Hi [email protected],

You have been invited.


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

The ActionMailer::Base.deliveries array is only reset automatically in 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

12.3 Functional and System Testing

Unit testing allows us to test the attributes of the email while functional and system testing allows us to test whether user interactions appropriately trigger the email to be delivered. For example, you can check that the invite friend operation is sending an email appropriately:

# Integration Test
require "test_helper"

class UsersControllerTest < ActionDispatch::IntegrationTest
  test "invite friend" do
    # Asserts the difference in the ActionMailer::Base.deliveries
    assert_emails 1 do
      post invite_friend_url, params: { email: "[email protected]" }
# System Test
require "test_helper"

class UsersTest < ActionDispatch::SystemTestCase
  driven_by :selenium, using: :headless_chrome

  test "inviting a friend" do
    visit invite_users_url
    fill_in "Email", with: "[email protected]"
    assert_emails 1 do
      click_on "Invite"

The assert_emails method is not tied to a particular deliver method and will work with emails delivered with either the deliver_now or deliver_later method. If we explicitly want to assert that the email has been enqueued we can use the assert_enqueued_emails method. More information can be found in the documentation here.

13 Testing Jobs

Since your custom jobs can be queued at different levels inside your application, you'll need to test both the jobs themselves (their behavior when they get enqueued) and that other entities correctly enqueue them.

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

require "test_helper"

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

This test is pretty simple and only asserts that the job got 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.

13.2 Custom Assertions and Testing Jobs inside Other Components

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.

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:

require "test_helper"

class ProductTest < ActiveSupport::TestCase
  include ActiveJob::TestHelper

  test "billing job scheduling" do
    assert_enqueued_with(job: BillingJob) do

14 Testing Action Cable

Since Action Cable is used at different levels inside your application, you'll need to test both the channels, connection classes themselves, and that other entities broadcast correct messages.

14.1 Connection Test Case

By default, when you generate new Rails application with Action Cable, a test for the base connection class (ApplicationCable::Connection) is generated as well under test/channels/application_cable directory.

Connection tests aim to check whether a connection's identifiers get assigned properly or that any improper connection requests are rejected. Here is an example:

class ApplicationCable::ConnectionTest < ActionCable::Connection::TestCase
  test "connects with params" do
    # Simulate a connection opening by calling the `connect` method
    connect params: { user_id: 42 }

    # You can access the Connection object via `connection` in tests
    assert_equal connection.user_id, "42"

  test "rejects connection without params" do
    # Use `assert_reject_connection` matcher to verify that
    # connection is rejected
    assert_reject_connection { connect }

You can also specify request cookies the same way you do in integration tests:

test "connects with cookies" do
  cookies.signed[:user_id] = "42"


  assert_equal connection.user_id, "42"

See the API documentation for ActionCable::Connection::TestCase for more information.

14.2 Channel Test Case

By default, when you generate a channel, an associated test will be generated as well under the test/channels directory. Here's an example test with a chat channel:

require "test_helper"

class ChatChannelTest < ActionCable::Channel::TestCase
  test "subscribes and stream for room" do
    # Simulate a subscription creation by calling `subscribe`
    subscribe room: "15"

    # You can access the Channel object via `subscription` in tests
    assert subscription.confirmed?
    assert_has_stream "chat_15"

This test is pretty simple and only asserts that the channel subscribes the connection to a particular stream.

You can also specify the underlying connection identifiers. Here's an example test with a web notifications channel:

require "test_helper"

class WebNotificationsChannelTest < ActionCable::Channel::TestCase
  test "subscribes and stream for user" do
    stub_connection current_user: users(:john)


    assert_has_stream_for users(:john)

See the API documentation for ActionCable::Channel::TestCase for more information.

14.3 Custom Assertions And Testing Broadcasts Inside Other Components

Action Cable 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 ActionCable::TestHelper.

It's a good practice to ensure that the correct message has been broadcasted inside other components (e.g. inside your controllers). This is precisely where the custom assertions provided by Action Cable are pretty useful. For instance, within a model:

require "test_helper"

class ProductTest < ActionCable::TestCase
  test "broadcast status after charge" do
    assert_broadcast_on("products:#{product.id}", type: "charged") do

If you want to test the broadcasting made with Channel.broadcast_to, you should use Channel.broadcasting_for to generate an underlying stream name:

# app/jobs/chat_relay_job.rb
class ChatRelayJob < ApplicationJob
  def perform_later(room, message)
    ChatChannel.broadcast_to room, text: message
# test/jobs/chat_relay_job_test.rb
require "test_helper"

class ChatRelayJobTest < ActiveJob::TestCase
  include ActionCable::TestHelper

  test "broadcast message to room" do
    room = rooms(:all)

    assert_broadcast_on(ChatChannel.broadcasting_for(room), text: "Hi!") do
      ChatRelayJob.perform_now(room, "Hi!")

15 Recursos Adicionais para Testes

15.1 Testando Código Dependente de Data/Horário

O Rails fornece métodos helpers integrados que permitem que você verifique que seu código dependente de data ou hora funcione conforme o esperado.

Aqui está um exemplo utilizando o helper travel_to:

# Digamos que um usuário só poderá enviar presentes após um mês do seu registro.
user = User.create(name: "Gaurish", activation_date: Date.new(2004, 10, 24))
assert_not user.applicable_for_gifting?
travel_to Date.new(2004, 11, 24) do
  assert_equal Date.new(2004, 10, 24), user.activation_date # dentro do bloco `travel_to` é feito o mock de `Date.current` 
  assert user.applicable_for_gifting?
assert_equal Date.new(2004, 10, 24), user.activation_date # A mudança é visível somente dentro do bloco `travel_to`.

Por favor consulte a Documentação da API ActiveSupport::Testing::TimeHelpers para obter informações detalhadas sobre os helpers de tempo disponíveis.


Você é incentivado a ajudar a melhorar a qualidade deste guia.

Por favor, contribua se vir qualquer erros, inclusive erros de digitação. Para começar, você pode ler nossa sessão de contribuindo com a documentação.

Você também pode encontrar conteúdo incompleto ou coisas que não estão atualizadas. Por favor, adicione qualquer documentação em falta na main do Rails. Certifique-se de checar o Edge Guides (en-US) primeiro para verificar se o problema já foi resolvido ou não no branch main. Verifique as Diretrizes do Guia Ruby on Rails para estilo e convenções.

Se, por qualquer motivo, você encontrar algo para consertar, mas não conseguir consertá-lo, por favor abra uma issue no nosso Guia.

E por último, mas não menos importante, qualquer tipo de discussão sobre a documentação do Ruby on Rails é muito bem vinda na lista de discussão rubyonrails-docs e nas issues do Guia em português.

dark theme icon