From 150630e747dae96746b0ee7c4a6952c1052e9ef2 Mon Sep 17 00:00:00 2001 From: harriet oughton Date: Thu, 12 Sep 2024 19:08:26 +0100 Subject: [PATCH 01/31] Update Overall Structure and Headings --- guides/source/testing.md | 298 +++++++++++++++++++-------------------- 1 file changed, 149 insertions(+), 149 deletions(-) diff --git a/guides/source/testing.md b/guides/source/testing.md index e4ded0b79fc02..4043dc084e172 100644 --- a/guides/source/testing.md +++ b/guides/source/testing.md @@ -13,8 +13,8 @@ After reading this guide, you will know: -------------------------------------------------------------------------------- -Why Write Tests for Your Rails Applications? --------------------------------------------- +Why Write Tests? +---------------- Rails makes it super easy to write your tests. It starts by producing skeleton test code while you are creating your models and controllers. @@ -27,7 +27,7 @@ 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. -### Rails Sets up for Testing from the Word Go +### Test Setup 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: @@ -347,7 +347,7 @@ Because of the modular nature of the testing framework, it is possible to create NOTE: Creating your own assertions is an advanced topic that we won't cover in this tutorial. -### Rails Specific Assertions +### Rails-Specific Assertions Rails adds some custom assertions of its own to the `minitest` framework: @@ -383,7 +383,7 @@ Rails adds some custom assertions of its own to the `minitest` framework: You'll see the usage of some of these assertions in the next chapter. -### A Brief Note About Test Cases +### 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: @@ -546,142 +546,6 @@ Known extensions: rails, pride -p, --pride Pride. Show your testing pride! ``` -### Running tests in Continuous Integration (CI) - -To run all tests in a CI environment, there's just one command you need: - -```bash -$ bin/rails test -``` - -If you are using [System Tests](#system-testing), `bin/rails test` will not run them, since -they can be slow. To also run them, add an another CI step that runs `bin/rails test:system`, -or change your first step to `bin/rails test:all`, which runs all tests including system tests. - -Parallel Testing ----------------- - -Parallel testing allows you to parallelize your test suite. While forking processes is the -default method, threading is supported as well. Running tests in parallel reduces the time it -takes your entire test suite to run. - -### Parallel Testing with Processes - -The default parallelization method is to fork processes using Ruby's DRb system. The processes -are forked based on the number of workers provided. The default number is the actual core count -on the machine you are on, but can be changed by the number passed to the parallelize method. - -To enable parallelization add the following to your `test_helper.rb`: - -```ruby -class ActiveSupport::TestCase - parallelize(workers: 2) -end -``` - -The number of workers passed is the number of times the process will be forked. You may want to -parallelize your local test suite differently from your CI, so an environment variable is provided -to be able to easily change the number of workers a test run should use: - -```bash -$ PARALLEL_WORKERS=15 bin/rails test -``` - -When parallelizing tests, Active Record automatically handles creating a database and loading the schema into the database for each -process. The databases will be suffixed with the number corresponding to the worker. For example, if you -have 2 workers the tests will create `test-database-0` and `test-database-1` respectively. - -If the number of workers passed is 1 or fewer the processes will not be forked and the tests will not -be parallelized and they will use the original `test-database` database. - -Two hooks are provided, one runs when the process is forked, and one runs before the forked process is closed. -These can be useful if your app uses multiple databases or performs other tasks that depend on the number of -workers. - -The `parallelize_setup` method is called right after the processes are forked. The `parallelize_teardown` method -is called right before the processes are closed. - -```ruby -class ActiveSupport::TestCase - parallelize_setup do |worker| - # setup databases - end - - parallelize_teardown do |worker| - # cleanup databases - end - - parallelize(workers: :number_of_processors) -end -``` - -These methods are not needed or available when using parallel testing with threads. - -### Parallel Testing with Threads - -If you prefer using threads or are using JRuby, a threaded parallelization option is provided. The threaded -parallelizer is backed by Minitest's `Parallel::Executor`. - -To change the parallelization method to use threads over forks put the following in your `test_helper.rb`: - -```ruby -class ActiveSupport::TestCase - parallelize(workers: :number_of_processors, with: :threads) -end -``` - -Rails applications generated from JRuby or TruffleRuby will automatically include the `with: :threads` option. - -The number of workers passed to `parallelize` determines the number of threads the tests will use. You may -want to parallelize your local test suite differently from your CI, so an environment variable is provided -to be able to easily change the number of workers a test run should use: - -```bash -$ PARALLEL_WORKERS=15 bin/rails test -``` - -### Testing Parallel Transactions - -When you want to test code that runs parallel database transactions in threads, -those can block each other because they are already nested under the implicit -test transaction. - -To workaround this, you can disable transactions in a test case class by setting -`self.use_transactional_tests = false`: - -```ruby -class WorkerTest < ActiveSupport::TestCase - self.use_transactional_tests = false - - test "parallel transactions" do - # start some threads that create transactions - end -end -``` - -NOTE: With disabled transactional tests, you have to clean up any data tests -create as changes are not automatically rolled back after the test completes. - -### Threshold to parallelize tests - -Running tests in parallel adds an overhead in terms of database setup and -fixture loading. Because of this, Rails won't parallelize executions that involve -fewer than 50 tests. - -You can configure this threshold in your `test.rb`: - -```ruby -config.active_support.test_parallelization_threshold = 100 -``` - -And also when setting up parallelization at the test case level: - -```ruby -class ActiveSupport::TestCase - parallelize threshold: 100 -end -``` - The Test Database ----------------- @@ -704,7 +568,7 @@ bring the schema up to date. NOTE: If there were modifications to existing migrations, the test database needs to be rebuilt. This can be done by executing `bin/rails test:db`. -### The Low-Down on Fixtures +### Fixtures For good tests, you'll need to give some thought to setting up test data. In Rails, you can handle this by defining and customizing fixtures. @@ -1253,7 +1117,7 @@ Finally we can assert that our response was successful and our new article is re 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. -Functional Tests for Your Controllers +Functional Tests for 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. @@ -1610,7 +1474,8 @@ 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. -### Test Helpers +Test Helpers +------------ To avoid code duplication, you can add your own test helpers. Sign in helper can be a good example: @@ -1767,8 +1632,7 @@ assert_select_email do end ``` -Testing View Partials ---------------------- +### Testing View Partials Partial templates - usually called "partials" - are another device for breaking the rendering process into more manageable chunks. With partials, you can extract pieces of code from your templates to separate files and reuse them throughout your templates. @@ -1917,8 +1781,7 @@ end [rails-dom-testing]: https://github.com/rails/rails-dom-testing [RSS content]: https://www.rssboard.org/rss-specification -Testing Helpers ---------------- +### Testing View Helpers A helper is just a simple module where you can define methods which are available in your views. @@ -1952,7 +1815,7 @@ end Moreover, since the test class extends from `ActionView::TestCase`, you have access to Rails' helper methods such as `link_to` or `pluralize`. -Testing Your Mailers +Testing Mailers -------------------- Testing mailer classes requires some specific tools to do a thorough job. @@ -2366,6 +2229,143 @@ class ChatRelayJobTest < ActiveJob::TestCase end ``` +Running tests in Continuous Integration (CI) +-------------------------------------------- + +To run all tests in a CI environment, there's just one command you need: + +```bash +$ bin/rails test +``` + +If you are using [System Tests](#system-testing), `bin/rails test` will not run them, since +they can be slow. To also run them, add an another CI step that runs `bin/rails test:system`, +or change your first step to `bin/rails test:all`, which runs all tests including system tests. + +Parallel Testing +---------------- + +Parallel testing allows you to parallelize your test suite. While forking processes is the +default method, threading is supported as well. Running tests in parallel reduces the time it +takes your entire test suite to run. + +### Parallel Testing with Processes + +The default parallelization method is to fork processes using Ruby's DRb system. The processes +are forked based on the number of workers provided. The default number is the actual core count +on the machine you are on, but can be changed by the number passed to the parallelize method. + +To enable parallelization add the following to your `test_helper.rb`: + +```ruby +class ActiveSupport::TestCase + parallelize(workers: 2) +end +``` + +The number of workers passed is the number of times the process will be forked. You may want to +parallelize your local test suite differently from your CI, so an environment variable is provided +to be able to easily change the number of workers a test run should use: + +```bash +$ PARALLEL_WORKERS=15 bin/rails test +``` + +When parallelizing tests, Active Record automatically handles creating a database and loading the schema into the database for each +process. The databases will be suffixed with the number corresponding to the worker. For example, if you +have 2 workers the tests will create `test-database-0` and `test-database-1` respectively. + +If the number of workers passed is 1 or fewer the processes will not be forked and the tests will not +be parallelized and they will use the original `test-database` database. + +Two hooks are provided, one runs when the process is forked, and one runs before the forked process is closed. +These can be useful if your app uses multiple databases or performs other tasks that depend on the number of +workers. + +The `parallelize_setup` method is called right after the processes are forked. The `parallelize_teardown` method +is called right before the processes are closed. + +```ruby +class ActiveSupport::TestCase + parallelize_setup do |worker| + # setup databases + end + + parallelize_teardown do |worker| + # cleanup databases + end + + parallelize(workers: :number_of_processors) +end +``` + +These methods are not needed or available when using parallel testing with threads. + +### Parallel Testing with Threads + +If you prefer using threads or are using JRuby, a threaded parallelization option is provided. The threaded +parallelizer is backed by Minitest's `Parallel::Executor`. + +To change the parallelization method to use threads over forks put the following in your `test_helper.rb`: + +```ruby +class ActiveSupport::TestCase + parallelize(workers: :number_of_processors, with: :threads) +end +``` + +Rails applications generated from JRuby or TruffleRuby will automatically include the `with: :threads` option. + +The number of workers passed to `parallelize` determines the number of threads the tests will use. You may +want to parallelize your local test suite differently from your CI, so an environment variable is provided +to be able to easily change the number of workers a test run should use: + +```bash +$ PARALLEL_WORKERS=15 bin/rails test +``` + +### Testing Parallel Transactions + +When you want to test code that runs parallel database transactions in threads, +those can block each other because they are already nested under the implicit +test transaction. + +To workaround this, you can disable transactions in a test case class by setting +`self.use_transactional_tests = false`: + +```ruby +class WorkerTest < ActiveSupport::TestCase + self.use_transactional_tests = false + + test "parallel transactions" do + # start some threads that create transactions + end +end +``` + +NOTE: With disabled transactional tests, you have to clean up any data tests +create as changes are not automatically rolled back after the test completes. + +### Threshold to parallelize tests + +Running tests in parallel adds an overhead in terms of database setup and +fixture loading. Because of this, Rails won't parallelize executions that involve +fewer than 50 tests. + +You can configure this threshold in your `test.rb`: + +```ruby +config.active_support.test_parallelization_threshold = 100 +``` + +And also when setting up parallelization at the test case level: + +```ruby +class ActiveSupport::TestCase + parallelize threshold: 100 +end +``` + Testing Eager Loading --------------------- From eb5381ca9cb33a22eb911472314da8f8f230ab44 Mon Sep 17 00:00:00 2001 From: harriet oughton Date: Thu, 12 Sep 2024 19:26:26 +0100 Subject: [PATCH 02/31] Adjust wording and grammar for readability and understanding --- guides/source/testing.md | 50 ++++++++++++++++++++++------------------ 1 file changed, 27 insertions(+), 23 deletions(-) diff --git a/guides/source/testing.md b/guides/source/testing.md index 4043dc084e172..875951407596f 100644 --- a/guides/source/testing.md +++ b/guides/source/testing.md @@ -20,12 +20,12 @@ Rails makes it super easy to write your tests. It starts by producing skeleton t By 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. +Rails tests can also simulate browser requests and thus you can test your application's response without having to view the output 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. +Testing wasn't just an afterthought - it was woven into the Rails fabric from the very beginning. ### Test Setup @@ -37,7 +37,9 @@ application_system_test_case.rb controllers/ helpers/ 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. +### Test Directories + +The `helpers`, `mailers`, and `models` directories are where tests for view helpers, mailers, and models respectively should be stored. The `channels` directory is where tests for Action Cable connection and channels should be stored. The `controllers` directory is where tests for controllers, routes, and views should be stored. The `integration` directory is where tests for interactions between controllers should be stored. 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 @@ -45,7 +47,7 @@ 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. +Fixtures are a way of organizing test data; they can be stored in the `fixtures` directory. A `jobs` directory will also be created when an associated test is first generated. @@ -64,16 +66,14 @@ NOTE: Your tests are run under `RAILS_ENV=test`. ### Rails Meets Minitest -If you remember, we used the `bin/rails generate model` command in the -[Getting Started with Rails](getting_started.html) guide. We created our first -model, and among other things it created test stubs in the `test` directory: +We introduced the `bin/rails generate model` command in the +[Getting Started with Rails](getting_started.html#mvc-and-you-generating-a-model) guide. Alongside creating a model, this command also creates a test stub in the `test` directory: ```bash $ 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 ... ``` @@ -103,7 +103,7 @@ class ArticleTest < ActiveSupport::TestCase end ``` -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. +This is called a test case, because the `ArticleTest` class inherits from `ActiveSupport::TestCase`. It therefore also has all the methods from `ActiveSupport::TestCase` available to it. Later in this guide, we'll see some of the methods this 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. @@ -145,7 +145,7 @@ Every test may contain one or more assertions, with no restriction as to how man #### 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. +To see how a test failure is reported, you can add a failing test to the `article_test.rb` test case. Here were are asserting that the article will not save, which will fail the test when the article saves successfully. ```ruby test "should not save article without title" do @@ -158,6 +158,7 @@ Let us run this newly added test (where `6` is the line number where the test is ```bash $ bin/rails test test/models/article_test.rb:6 +Running 1 tests in a single process (parallelization threshold is 50) Run options: --seed 44656 # Running: @@ -195,7 +196,7 @@ ArticleTest#test_should_not_save_article_without_title [/path/to/blog/test/model Saved the article without a title ``` -Now to get this test to pass we can add a model level validation for the _title_ field. +To get this test to pass we can add a model level validation for the `title` field. ```ruby class Article < ApplicationRecord @@ -203,10 +204,11 @@ class Article < ApplicationRecord end ``` -Now the test should pass. Let us verify by running the test again: +Now the test should pass, as we have not initialized the article in our test with a `title`, so the model validation will prevent the save. Let us verify by running the test again: ```bash $ bin/rails test test/models/article_test.rb:6 +Running 1 tests in a single process (parallelization threshold is 50) Run options: --seed 31252 # Running: @@ -218,13 +220,14 @@ 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 +The small green dot displayed means that the test has passed successfully. + +NOTE: In that process, 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). +referred to as _Test-Driven Development_ (TDD). -#### What an Error Looks Like +#### Encountering and Asserting Error-Presence To see how an error gets reported, here's a test containing an error: @@ -240,11 +243,12 @@ Now you can see even more output in the console from running the tests: ```bash $ bin/rails test test/models/article_test.rb +Running 2 tests in a single process (parallelization threshold is 50) Run options: --seed 1808 # Running: -.E +E Error: ArticleTest#test_should_report_error: @@ -254,14 +258,14 @@ NameError: undefined local variable or method 'some_undefined_variable' for # Date: Tue, 17 Sep 2024 16:51:56 +0100 Subject: [PATCH 03/31] Add assert_routing to Rails assertions --- guides/source/testing.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/guides/source/testing.md b/guides/source/testing.md index 875951407596f..603f287612cf7 100644 --- a/guides/source/testing.md +++ b/guides/source/testing.md @@ -364,6 +364,7 @@ Rails adds some custom assertions of its own to the `minitest` framework: | [`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_routing(expected_path, options, defaults={}, extras = {}, message=nil)`][] | Asserts that `path` and `options` match both ways; in other words, it verifies that `path` generates `options` and then that `options` generates `path`. This essentially combines `assert_recognizes` and `assert_generates` into one step. The extras hash allows you to specify options that would normally be provided as a query string to the action. The message parameter allows you to specify a custom error message to display upon failure.| | [`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](https://rubydoc.info/gems/rack/Rack/Utils#HTTP_STATUS_CODES-constant) and how their [mapping](https://rubydoc.info/gems/rack/Rack/Utils#SYMBOL_TO_STATUS_CODE-constant) 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`.| | [`assert_queries_count(count = nil, include_schema: false, &block)`][] | Asserts that `&block` generates an `int` number of SQL queries.| @@ -378,6 +379,7 @@ Rails adds some custom assertions of its own to the `minitest` framework: [`assert_nothing_raised { block }`]: https://api.rubyonrails.org/classes/ActiveSupport/Testing/Assertions.html#method-i-assert_nothing_raised [`assert_recognizes(expected_options, path, extras={}, message=nil)`]: https://api.rubyonrails.org/classes/ActionDispatch/Assertions/RoutingAssertions.html#method-i-assert_recognizes [`assert_generates(expected_path, options, defaults={}, extras = {}, message=nil)`]: https://api.rubyonrails.org/classes/ActionDispatch/Assertions/RoutingAssertions.html#method-i-assert_generates +[`assert_routing(expected_path, options, defaults={}, extras = {}, message=nil)`]: https://api.rubyonrails.org/classes/ActionDispatch/Assertions/RoutingAssertions.html#method-i-assert_routing [`assert_response(type, message = nil)`]: https://api.rubyonrails.org/classes/ActionDispatch/Assertions/ResponseAssertions.html#method-i-assert_response [`assert_redirected_to(options = {}, message=nil)`]: https://api.rubyonrails.org/classes/ActionDispatch/Assertions/ResponseAssertions.html#method-i-assert_redirected_to [`assert_queries_count(count = nil, include_schema: false, &block)`]: https://api.rubyonrails.org/classes/ActiveRecord/Assertions/QueryAssertions.html#method-i-assert_queries_count From e330d3333d47f6ff823b6083e6bdeb2360fdf6f5 Mon Sep 17 00:00:00 2001 From: harriet oughton Date: Wed, 25 Sep 2024 19:24:11 +0100 Subject: [PATCH 04/31] Further wording and grammar tweaks --- guides/source/testing.md | 40 +++++++++++++++++++--------------------- 1 file changed, 19 insertions(+), 21 deletions(-) diff --git a/guides/source/testing.md b/guides/source/testing.md index 603f287612cf7..907e0b16a2cba 100644 --- a/guides/source/testing.md +++ b/guides/source/testing.md @@ -389,7 +389,7 @@ Rails adds some custom assertions of its own to the `minitest` framework: You'll see the usage of some of these assertions in the next chapter. -### Test Cases +### Assertions in Our 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: @@ -397,20 +397,18 @@ All the basic assertions such as `assert_equal` defined in `Minitest::Assertions * [`ActionMailer::TestCase`](https://api.rubyonrails.org/classes/ActionMailer/TestCase.html) * [`ActionView::TestCase`](https://api.rubyonrails.org/classes/ActionView/TestCase.html) * [`ActiveJob::TestCase`](https://api.rubyonrails.org/classes/ActiveJob/TestCase.html) -* [`ActionDispatch::IntegrationTest`](https://api.rubyonrails.org/classes/ActionDispatch/IntegrationTest.html) +* [`ActionDispatch::Integration::Session`](https://api.rubyonrails.org/classes/ActionDispatch/Integration/Session.html) * [`ActionDispatch::SystemTestCase`](https://api.rubyonrails.org/classes/ActionDispatch/SystemTestCase.html) * [`Rails::Generators::TestCase`](https://api.rubyonrails.org/classes/Rails/Generators/TestCase.html) Each of these classes include `Minitest::Assertions`, allowing us to use all of the basic assertions in our tests. -NOTE: For more information on `Minitest`, refer to [its -documentation](http://docs.seattlerb.org/minitest). +NOTE: For more information on `Minitest`, refer to its [documentation](http://docs.seattlerb.org/minitest). ### Transactions By default, Rails automatically wraps tests in a database transaction that is -rolled back after they finish. This makes tests independent of each other and -changes to the database are only visible within a single test. +rolled back after they finish. This makes tests independent of each other and means that changes to the database are only visible within a single test. ```ruby class MyTest < ActiveSupport::TestCase @@ -429,7 +427,7 @@ though: class MyTest < ActiveSupport::TestCase test "current_transaction" do # The implicit transaction around tests does not interfere with the - # application-level semantics of current_transaction. + # application-level semantics of the current_transaction. assert User.current_transaction.blank? end end @@ -458,6 +456,7 @@ Or we can run a single test file by passing the `bin/rails test` command the fil ```bash $ bin/rails test test/models/article_test.rb +Running 1 tests in a single process (parallelization threshold is 50) Run options: --seed 1559 # Running: @@ -476,6 +475,7 @@ You can also run a particular test method from the test case by providing the ```bash $ bin/rails test test/models/article_test.rb -n test_the_truth +Running 1 tests in a single process (parallelization threshold is 50) Run options: -n test_the_truth --seed 43583 # Running: @@ -535,7 +535,6 @@ minitest options: --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. - -q, --quiet Quiet. Show no progress processing files. --show-skips Show skipped at the end of run. -n, --name PATTERN Filter run on /regexp/ or string. --exclude PATTERN Exclude /regexp/ or string from run. @@ -586,7 +585,7 @@ _Fixtures_ is a fancy word for sample data. Fixtures allow you to populate your NOTE: Fixtures are not designed to create every object that your tests need, and are best managed when only used for default data that can be applied to the common case. -You'll find fixtures under your `test/fixtures` directory. When you run `bin/rails generate model` to create a new model, Rails automatically creates fixture stubs in this directory. +Fixtures can be stored in your `test/fixtures` directory. #### YAML @@ -659,7 +658,7 @@ first: title: An Article ``` -Assuming that there is an [image/png][] encoded file at +Assuming that there is an image/png encoded file at `test/fixtures/files/first.png`, the following YAML fixture entries will generate the related `ActiveStorage::Blob` and `ActiveStorage::Attachment` records: @@ -679,7 +678,7 @@ first_thumbnail_attachment: [image/png]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types#image_types -#### ERB'in It Up +#### ERB and Fixtures 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: @@ -704,7 +703,7 @@ TIP: In order to remove existing data from the database, Rails tries to disable #### Fixtures are Active Record Objects -Fixtures are instances of Active Record. As mentioned in point #3 above, you can access the object directly because it is automatically available as a method whose scope is local of the test case. For example: +Fixtures are instances of Active Record. As mentioned above, you can access the object directly because it is automatically available as a method whose scope is local of the test case. For example: ```ruby # this will return the User object for the fixture named david @@ -729,7 +728,7 @@ users(:david, :steve) Model Testing ------------- -Model tests are used to test the various models of your application. +Model tests are used to test the various models of your application and their associated logic. Rails model tests are stored under the `test/models` directory. Rails provides a generator to create a model test skeleton for you. @@ -737,7 +736,6 @@ a generator to create a model test skeleton for you. ```bash $ bin/rails generate test_unit:model article title:string body:text create test/models/article_test.rb -create test/fixtures/articles.yml ``` Model tests don't have their own superclass like `ActionMailer::TestCase`. Instead, they inherit from [`ActiveSupport::TestCase`](https://api.rubyonrails.org/classes/ActiveSupport/TestCase.html). @@ -746,7 +744,7 @@ System Testing -------------- System tests allow you to test user interactions with your application, running tests -in either a real or a headless browser. System tests use Capybara under the hood. +in either a real or a headless browser (which runs in the background without opening a visible window). System tests use Capybara under the hood. For creating Rails system tests, you use the `test/system` directory in your application. Rails provides a generator to create a system test skeleton for you. @@ -827,7 +825,7 @@ end If you want to use a remote browser, e.g. [Headless Chrome in Docker](https://github.com/SeleniumHQ/docker-selenium), -you have to add remote `url` and set `browser` as remote through `options`. +you have to add a remote `url` and set `browser` as remote through `options`. ```ruby require "test_helper" @@ -843,13 +841,13 @@ class ApplicationSystemTestCase < ActionDispatch::SystemTestCase end ``` -Now you should get a connection to remote browser. +Now you should get a connection to the remote browser. ```bash $ SELENIUM_REMOTE_URL=http://localhost:4444/wd/hub bin/rails test:system ``` -If your application in test is running remote too, e.g. Docker container, +If your application in test is running remote too, e.g. within a Docker container, Capybara needs more input about how to [call remote servers](https://github.com/teamcapybara/capybara#calling-remote-servers). @@ -866,8 +864,8 @@ class ApplicationSystemTestCase < ActionDispatch::SystemTestCase end ``` -Now you should get a connection to remote browser and server, regardless if it -is running in Docker container or CI. +Now you should get a connection to a remote browser and server, regardless if it +is running in a Docker container or CI. If your Capybara configuration requires more setup than provided by Rails, this additional configuration could be added into the `application_system_test_case.rb` @@ -878,7 +876,7 @@ for additional settings. ### Screenshot Helper -The `ScreenshotHelper` is a helper designed to capture screenshots of your tests. +The [`ScreenshotHelper`](https://api.rubyonrails.org/v5.1.7/classes/ActionDispatch/SystemTesting/TestHelpers/ScreenshotHelper.html) is a helper designed to capture screenshots of your tests. This can be helpful for viewing the browser at the point a test failed, or to view screenshots later for debugging. From da6ae6090a8197be9236f80726a08edb0540085b Mon Sep 17 00:00:00 2001 From: harriet oughton Date: Fri, 27 Sep 2024 18:25:04 +0100 Subject: [PATCH 05/31] Adjust location of screenshot helper section --- guides/source/testing.md | 28 +++++++++++++--------------- 1 file changed, 13 insertions(+), 15 deletions(-) diff --git a/guides/source/testing.md b/guides/source/testing.md index 907e0b16a2cba..73f474e9243f8 100644 --- a/guides/source/testing.md +++ b/guides/source/testing.md @@ -874,19 +874,6 @@ file. Please see [Capybara's documentation](https://github.com/teamcapybara/capybara#setup) for additional settings. -### Screenshot Helper - -The [`ScreenshotHelper`](https://api.rubyonrails.org/v5.1.7/classes/ActionDispatch/SystemTesting/TestHelpers/ScreenshotHelper.html) is a helper designed to capture screenshots of your tests. -This can be helpful for viewing the browser at the point a test failed, or -to view screenshots later for debugging. - -Two methods are provided: `take_screenshot` and `take_failed_screenshot`. -`take_failed_screenshot` is automatically included in `before_teardown` inside -Rails. - -The `take_screenshot` helper method can be included anywhere in your tests to -take a screenshot of the browser. - ### Implementing a System Test Now we're going to add a system test to our blog application. We'll demonstrate @@ -993,11 +980,22 @@ class PostsTest < MobileSystemTestCase end end ``` +#### Screenshot Helper + +The [`ScreenshotHelper`](https://api.rubyonrails.org/v5.1.7/classes/ActionDispatch/SystemTesting/TestHelpers/ScreenshotHelper.html) is a helper designed to capture screenshots of your tests. +This can be helpful for viewing the browser at the point a test failed, or +to view screenshots later for debugging. + +Two methods are provided: `take_screenshot` and `take_failed_screenshot`. +`take_failed_screenshot` is automatically included in `before_teardown` inside +Rails. + +The `take_screenshot` helper method can be included anywhere in your tests to +take a screenshot of the browser. #### Taking It Further -The beauty of system testing is that it is similar to integration testing in -that it tests the user's interaction with your controller, model, and view, but +The beauty of system testing is that it is similar to [integration testing](testing.html#integration-testing) in that it tests the user's interaction with your controller, model, and view, but system testing is much more robust and actually tests your application as if a real user were using it. Going forward, you can test anything that the user themselves would do in your application such as commenting, deleting articles, From d8da27d41bf884f451f332e030f7db94ad860f0b Mon Sep 17 00:00:00 2001 From: harriet oughton Date: Mon, 30 Sep 2024 18:28:55 +0100 Subject: [PATCH 06/31] Move errors paragraph to additional testing resources section --- guides/source/testing.md | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/guides/source/testing.md b/guides/source/testing.md index 73f474e9243f8..32abab3f6d6f6 100644 --- a/guides/source/testing.md +++ b/guides/source/testing.md @@ -773,8 +773,6 @@ By default, system tests are run with the Selenium driver, using the Chrome browser, and a screen size of 1400x1400. The next section explains how to change the default settings. -By default, Rails will attempt to rescue from exceptions raised during tests and respond with HTML error pages. This behavior can be controlled by the [`config.action_dispatch.show_exceptions`](/configuring.html#config-action-dispatch-show-exceptions) configuration. - ### Changing the Default Settings Rails makes changing the default settings for system tests very simple. All @@ -997,20 +995,20 @@ take a screenshot of the browser. The beauty of system testing is that it is similar to [integration testing](testing.html#integration-testing) in that it tests the user's interaction with your controller, model, and view, but system testing is much more robust and actually tests your application as if -a real user were using it. Going forward, you can test anything that the user +a real user were using it. With system tests, you can test anything that the user themselves would do in your application such as commenting, deleting articles, publishing draft articles, etc. 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. +Integration tests are another way of testing 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. +Rails integration tests can be created in the `test/integration` directory. Rails provides a generator to create an integration test skeleton for us. ```bash $ bin/rails generate integration_test user_flows - exists test/integration/ + invoke test_unit create test/integration/user_flows_test.rb ``` @@ -1028,8 +1026,6 @@ end Here the test is inheriting from `ActionDispatch::IntegrationTest`. This makes some additional helpers available for us to use in our integration tests. -By default, Rails will attempt to rescue from exceptions raised during tests and respond with HTML error pages. This behavior can be controlled by the [`config.action_dispatch.show_exceptions`](/configuring.html#config-action-dispatch-show-exceptions) configuration. - ### 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. @@ -1229,8 +1225,6 @@ NOTE: If you followed the steps in the [Basic Authentication](getting_started.ht post articles_url, params: { article: { body: "Rails is awesome!", title: "Hello Rails" } }, headers: { Authorization: ActionController::HttpAuthentication::Basic.encode_credentials("dhh", "secret") } ``` -By default, Rails will attempt to rescue from exceptions raised during tests and respond with HTML error pages. This behavior can be controlled by the [`config.action_dispatch.show_exceptions`](/configuring.html#config-action-dispatch-show-exceptions) configuration. - ### 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: @@ -2419,6 +2413,10 @@ end Additional Testing Resources ---------------------------- +### Errors + +In system tests, integration tests and functional controller tests, Rails will attempt to rescue from exceptions raised and respond with HTML error pages by default. This behavior can be controlled by the [`config.action_dispatch.show_exceptions`](/configuring.html#config-action-dispatch-show-exceptions) configuration. + ### Testing Time-Dependent Code Rails provides built-in helper methods that enable you to assert that your time-sensitive code works as expected. From 42df99934a9d22d72897f8ade5a19928c9dedb9f Mon Sep 17 00:00:00 2001 From: harriet oughton Date: Mon, 30 Sep 2024 18:55:44 +0100 Subject: [PATCH 07/31] Move integration tests helpers section --- guides/source/testing.md | 25 ++++++++++++------------- 1 file changed, 12 insertions(+), 13 deletions(-) diff --git a/guides/source/testing.md b/guides/source/testing.md index 32abab3f6d6f6..a44cb46ce8cd2 100644 --- a/guides/source/testing.md +++ b/guides/source/testing.md @@ -1024,19 +1024,7 @@ class UserFlowsTest < ActionDispatch::IntegrationTest end ``` -Here the test is inheriting from `ActionDispatch::IntegrationTest`. This makes some additional helpers available for us to use in our integration tests. - -### 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`](https://api.rubyonrails.org/classes/ActionDispatch/Integration/Runner.html). - -When performing requests, we will have [`ActionDispatch::Integration::RequestHelpers`](https://api.rubyonrails.org/classes/ActionDispatch/Integration/RequestHelpers.html) available for our use. - -If we need to upload files, take a look at [`ActionDispatch::TestProcess::FixtureFile`](https://api.rubyonrails.org/classes/ActionDispatch/TestProcess/FixtureFile.html) to help. - -If we need to modify the session, or state of our integration test, take a look at [`ActionDispatch::Integration::Session`](https://api.rubyonrails.org/classes/ActionDispatch/Integration/Session.html) to help. +Here the test is inheriting from `ActionDispatch::IntegrationTest`. This makes some additional [helpers](testing.html#helpers-available-for-integration-tests) available for us to use in our integration tests, alongside the standard testing helpers. ### Implementing an Integration Test @@ -1114,6 +1102,17 @@ Finally we can assert that our response was successful and our new article is re 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. +### Helpers Available for Integration Tests + +Let's get briefly introduced to some of the helpers we can choose from. + +For dealing with the integration test runner, see [`ActionDispatch::Integration::Runner`](https://api.rubyonrails.org/classes/ActionDispatch/Integration/Runner.html). + +When performing requests, we will have [`ActionDispatch::Integration::RequestHelpers`](https://api.rubyonrails.org/classes/ActionDispatch/Integration/RequestHelpers.html) available for our use. + +If we need to upload files, take a look at [`ActionDispatch::TestProcess::FixtureFile`](https://api.rubyonrails.org/classes/ActionDispatch/TestProcess/FixtureFile.html) to help. + +If we need to modify the session, or state of our integration test, take a look at [`ActionDispatch::Integration::Session`](https://api.rubyonrails.org/classes/ActionDispatch/Integration/Session.html) to help. Functional Tests for Controllers ------------------------------------- From c0c0ce25f21196413d41f6552f2981662b9961e6 Mon Sep 17 00:00:00 2001 From: harriet oughton Date: Mon, 30 Sep 2024 19:41:45 +0100 Subject: [PATCH 08/31] Minor wording changes --- guides/source/testing.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/guides/source/testing.md b/guides/source/testing.md index a44cb46ce8cd2..7be2b9a92fd4d 100644 --- a/guides/source/testing.md +++ b/guides/source/testing.md @@ -1063,7 +1063,7 @@ When we visit our root path, we should see `welcome/index.html.erb` rendered for #### Creating Articles Integration -How about testing our ability to create a new article in our blog and see the resulting article. +We can also test our ability to create a new article in our blog and display the resulting article. ```ruby test "can create an article" do @@ -1104,7 +1104,7 @@ We were able to successfully test a very small workflow for visiting our blog an ### Helpers Available for Integration Tests -Let's get briefly introduced to some of the helpers we can choose from. +Let's get briefly introduced to some of the helpers we can choose from in our integration tests. For dealing with the integration test runner, see [`ActionDispatch::Integration::Runner`](https://api.rubyonrails.org/classes/ActionDispatch/Integration/Runner.html). @@ -1117,7 +1117,7 @@ If we need to modify the session, or state of our integration test, take a look Functional Tests for 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. +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. ### What to Include in Your Functional Tests From 575d0665f74de559d8c9bd022dbb2ca0beba66ba Mon Sep 17 00:00:00 2001 From: harriet oughton Date: Wed, 2 Oct 2024 19:14:37 +0100 Subject: [PATCH 09/31] Make changes to funtional tests section --- guides/source/testing.md | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/guides/source/testing.md b/guides/source/testing.md index 7be2b9a92fd4d..4058b732d76a7 100644 --- a/guides/source/testing.md +++ b/guides/source/testing.md @@ -1115,18 +1115,17 @@ If we need to upload files, take a look at [`ActionDispatch::TestProcess::Fixtur If we need to modify the session, or state of our integration test, take a look at [`ActionDispatch::Integration::Session`](https://api.rubyonrails.org/classes/ActionDispatch/Integration/Session.html) to help. Functional Tests for 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. +In Rails, a focus on 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 focusing on testing how your actions handle the requests and the expected result or response. Functional controller tests are sometimes used in cases where system tests are not appropriate, e.g., to confirm an API response. ### What to Include in Your Functional Tests -You should test for things such as: +You could 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: From 456974a2605185251b1461206190c59e25e4556b Mon Sep 17 00:00:00 2001 From: harriet oughton Date: Thu, 3 Oct 2024 19:26:40 +0100 Subject: [PATCH 10/31] Further wording and structural changes --- guides/source/testing.md | 858 ++++++++++++++++++++------------------- 1 file changed, 430 insertions(+), 428 deletions(-) diff --git a/guides/source/testing.md b/guides/source/testing.md index 4058b732d76a7..faea104f2679b 100644 --- a/guides/source/testing.md +++ b/guides/source/testing.md @@ -740,271 +740,368 @@ create test/models/article_test.rb Model tests don't have their own superclass like `ActionMailer::TestCase`. Instead, they inherit from [`ActiveSupport::TestCase`](https://api.rubyonrails.org/classes/ActiveSupport/TestCase.html). -System Testing --------------- +Functional Testing for Controllers +---------------------------------- -System tests allow you to test user interactions with your application, running tests -in either a real or a headless browser (which runs in the background without opening a visible window). System tests use Capybara under the hood. +In Rails, a focus on 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 focusing on testing how your actions handle the requests and the expected result or response. Functional controller tests are sometimes used in cases where system tests are not appropriate, e.g., to confirm an API response. -For creating Rails system tests, you use the `test/system` directory in your -application. Rails provides a generator to create a system test skeleton for you. +### What to Include in Your Functional Tests + +You could 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 information displayed in the response? + +The easiest way to see functional tests in action is to generate a controller using the scaffold generator: ```bash -$ bin/rails generate system_test users - invoke test_unit - create test/system/users_test.rb +$ 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 +... ``` -Here's what a freshly generated system test looks like: +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. -```ruby -require "application_system_test_case" +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: -class UsersTest < ApplicationSystemTestCase - # test "visiting the index" do - # visit users_url - # - # assert_selector "h1", text: "Users" - # end +```bash +$ 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`. + +```ruby +# articles_controller_test.rb +class ArticlesControllerTest < ActionDispatch::IntegrationTest + test "should get index" do + get articles_url + assert_response :success + end end ``` -By default, system tests are run with the Selenium driver, using the Chrome -browser, and a screen size of 1400x1400. The next section explains how to -change the default settings. +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. -### Changing the Default Settings +The `get` method kicks off the web request and populates the results into the `@response`. It can accept up to 6 arguments: -Rails makes changing the default settings for system tests very simple. All -the setup is abstracted away so you can focus on writing your tests. +* 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. -When you generate a new application or scaffold, an `application_system_test_case.rb` file -is created in the test directory. This is where all the configuration for your -system tests should live. +All of these keyword arguments are optional. -If you want to change the default settings you can change what the system -tests are "driven by". Say you want to change the driver from Selenium to -Cuprite. First add the `cuprite` gem to your `Gemfile`. Then in your -`application_system_test_case.rb` file do the following: +Example: Calling the `:show` action for the first `Article`, passing in an `HTTP_REFERER` header: ```ruby -require "test_helper" -require "capybara/cuprite" - -class ApplicationSystemTestCase < ActionDispatch::SystemTestCase - driven_by :cuprite -end +get article_url(Article.first), headers: { "HTTP_REFERER" => "http://example.com/home" } ``` -The driver name is a required argument for `driven_by`. The optional arguments -that can be passed to `driven_by` are `:using` for the browser (this will only -be used by Selenium), `:screen_size` to change the size of the screen for -screenshots, and `:options` which can be used to set options supported by the -driver. +Another example: Calling the `:update` action for the last `Article`, passing in new text for the `title` in `params`, as an Ajax request: ```ruby -require "test_helper" +patch article_url(Article.last), params: { article: { title: "updated" } }, xhr: true +``` -class ApplicationSystemTestCase < ActionDispatch::SystemTestCase - driven_by :selenium, using: :firefox -end +One more example: Calling the `:create` action to create a new article, passing in +text for the `title` in `params`, as JSON request: + +```ruby +post articles_path, params: { article: { title: "Ahoy!" } }, as: :json ``` -If you want to use a headless browser, you could use Headless Chrome or Headless Firefox by adding -`headless_chrome` or `headless_firefox` in the `:using` argument. +NOTE: If you try running the `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 the `test_should_create_article` test in `articles_controller_test.rb` so that all our tests pass: ```ruby -require "test_helper" +test "should create article" do + assert_difference("Article.count") do + post articles_url, params: { article: { body: "Rails is awesome!", title: "Hello Rails" } } + end -class ApplicationSystemTestCase < ActionDispatch::SystemTestCase - driven_by :selenium, using: :headless_chrome + assert_redirected_to article_path(Article.last) end ``` -If you want to use a remote browser, e.g. -[Headless Chrome in Docker](https://github.com/SeleniumHQ/docker-selenium), -you have to add a remote `url` and set `browser` as remote through `options`. +Now you can try running all the tests and they should pass. + +NOTE: If you followed the steps in the [Basic Authentication](getting_started.html#basic-authentication) section, you'll need to add authorization to every request header to get all the tests passing: ```ruby -require "test_helper" +post articles_url, params: { article: { body: "Rails is awesome!", title: "Hello Rails" } }, headers: { Authorization: ActionController::HttpAuthentication::Basic.encode_credentials("dhh", "secret") } +``` -class ApplicationSystemTestCase < ActionDispatch::SystemTestCase - url = ENV.fetch("SELENIUM_REMOTE_URL", nil) - options = if url - { browser: :remote, url: url } - else - { browser: :chrome } - end - driven_by :selenium, using: :headless_chrome, options: options +### 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. + +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. + +### Testing XHR (Ajax) Requests + +An AJAX request (Asynchronous Javscript and XML) is a type of request where information is sent over a server without the page reloading. To test Ajax requests, you can specify the `xhr: true` +option to `get`, `post`, `patch`, `put`, and `delete` methods. For example: + +```ruby +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 end ``` -Now you should get a connection to the remote browser. +### Testing Other Request Objects -```bash -$ SELENIUM_REMOTE_URL=http://localhost:4444/wd/hub bin/rails test:system +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: + +```ruby +flash["gordon"] # or flash[:gordon] +session["shmession"] # or session[:shmession] +cookies["are_good_for_u"] # or cookies[:are_good_for_u] ``` -If your application in test is running remote too, e.g. within a Docker container, -Capybara needs more input about how to -[call remote servers](https://github.com/teamcapybara/capybara#calling-remote-servers). +### 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 + ```ruby -require "test_helper" +class ArticlesControllerTest < ActionDispatch::IntegrationTest + test "should get index" do + get articles_url -class ApplicationSystemTestCase < ActionDispatch::SystemTestCase - def setup - Capybara.server_host = "0.0.0.0" # bind to all interfaces - Capybara.app_host = "http://#{IPSocket.getaddress(Socket.gethostname)}" if ENV["SELENIUM_REMOTE_URL"].present? - super + assert_equal "index", @controller.action_name + assert_equal "application/x-www-form-urlencoded", @request.media_type + assert_match "Articles", @response.body end - # ... end ``` -Now you should get a connection to a remote browser and server, regardless if it -is running in a Docker container or CI. +### Setting Headers and CGI Variables -If your Capybara configuration requires more setup than provided by Rails, this -additional configuration could be added into the `application_system_test_case.rb` -file. +HTTP headers are pieces of information sent along with HTTP requests to provide important metadata along with that request. +CGI variables are environment variables used to exchange information between the web server and the application. -Please see [Capybara's documentation](https://github.com/teamcapybara/capybara#setup) -for additional settings. +HTTP headers and CGI variables can be tested by being passed as headers: -### Implementing a System Test +```ruby +# setting an HTTP Header +get articles_url, headers: { "Content-Type": "text/plain" } # simulate the request with custom header -Now we're going to add a system test to our blog application. We'll demonstrate -writing a system test by visiting the index page and creating a new blog article. +# setting a CGI variable +get articles_url, headers: { "HTTP_REFERER": "http://example.com/home" } # simulate the request with custom env variable +``` -If you used the scaffold generator, a system test skeleton was automatically -created for you. If you didn't use the scaffold generator, start by creating a -system test skeleton. +### Testing `flash` Notices -```bash -$ bin/rails generate system_test articles -``` +If you remember from earlier, one of the three hash objects we have access to was `flash`. -It should have created a test file placeholder for us. With the output of the -previous command you should see: +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: + +```ruby +test "should create article" do + assert_difference("Article.count") do + post articles_url, params: { article: { title: "Some title" } } + end + assert_redirected_to article_path(Article.last) + assert_equal "Article was successfully created.", flash[:notice] +end ``` - invoke test_unit - create test/system/articles_test.rb + +If we run our test now, we should see a failure: + +```bash +$ bin/rails test test/controllers/articles_controller_test.rb -n test_should_create_article +Running 1 tests in a single process (parallelization threshold is 50) +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 [/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 ``` -Now let's open that file and write our first assertion: +Let's implement the flash message now in our controller. Our `:create` action should now look like this: ```ruby -require "application_system_test_case" +def create + @article = Article.new(article_params) -class ArticlesTest < ApplicationSystemTestCase - test "viewing the index" do - visit articles_path - assert_selector "h1", text: "Articles" + if @article.save + flash[:notice] = "Article was successfully created." + redirect_to @article + else + render "new" end end ``` -The test should see that there is an `h1` on the articles index page and pass. - -Run the system tests. +Now if we run our tests, we should see it pass: ```bash -$ bin/rails test:system -``` +$ bin/rails test test/controllers/articles_controller_test.rb -n test_should_create_article +Running 1 tests in a single process (parallelization threshold is 50) +Run options: -n test_should_create_article --seed 18981 -NOTE: By default, running `bin/rails test` won't run your system tests. -Make sure to run `bin/rails test:system` to actually run them. -You can also run `bin/rails test:all` to run all tests, including system tests. +# Running: -#### Creating Articles System Test +. -Now let's test the flow for creating a new article in our blog. +Finished in 0.081972s, 12.1993 runs/s, 48.7972 assertions/s. -```ruby -test "should create Article" do - visit articles_path +1 runs, 4 assertions, 0 failures, 0 errors, 0 skips +``` - click_on "New Article" +### Putting It Together - fill_in "Title", with: "Creating an Article" - fill_in "Body", with: "Created this article successfully!" +At this point our Articles controller tests the `:index` as well as `:new` and `:create` actions. What about dealing with existing data? - click_on "Create Article" +Let's write a test for the `:show` action: - assert_text "Creating an Article" +```ruby +test "should show article" do + article = articles(:one) + get article_url(article) + assert_response :success end ``` -The first step is to call `visit articles_path`. This will take the test to the -articles index page. - -Then the `click_on "New Article"` will find the "New Article" button on the -index page. This will redirect the browser to `/articles/new`. +Remember from our discussion earlier on fixtures, the `articles()` method will give us access to our Articles fixtures. -Then the test will fill in the title and body of the article with the specified -text. Once the fields are filled in, "Create Article" is clicked on which will -send a POST request to create the new article in the database. +How about deleting an existing Article? -We will be redirected back to the articles index page and there we assert -that the text from the new article's title is on the articles index page. +```ruby +test "should destroy article" do + article = articles(:one) + assert_difference("Article.count", -1) do + delete article_url(article) + end -#### Testing for Multiple Screen Sizes + assert_redirected_to articles_path +end +``` -If you want to test for mobile sizes on top of testing for desktop, -you can create another class that inherits from `ActionDispatch::SystemTestCase` and use it in your -test suite. In this example a file called `mobile_system_test_case.rb` is created -in the `/test` directory with the following configuration. +We can also add a test for updating an existing Article. ```ruby -require "test_helper" +test "should update article" do + article = articles(:one) -class MobileSystemTestCase < ActionDispatch::SystemTestCase - driven_by :selenium, using: :chrome, screen_size: [375, 667] + 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. + article.reload + assert_equal "updated", article.title end ``` -To use this configuration, create a test inside `test/system` that inherits from `MobileSystemTestCase`. -Now you can test your app using multiple different configurations. +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 the below. Disregard the other tests for now, we're leaving them out for brevity. ```ruby -require "mobile_system_test_case" +require "test_helper" -class PostsTest < MobileSystemTestCase - test "visiting the index" do - visit posts_url - assert_selector "h1", text: "Posts" +class ArticlesControllerTest < ActionDispatch::IntegrationTest + # called before every single test + setup do + @article = articles(:one) end -end -``` -#### Screenshot Helper -The [`ScreenshotHelper`](https://api.rubyonrails.org/v5.1.7/classes/ActionDispatch/SystemTesting/TestHelpers/ScreenshotHelper.html) is a helper designed to capture screenshots of your tests. -This can be helpful for viewing the browser at the point a test failed, or -to view screenshots later for debugging. + # called after every single test + teardown do + # when controller is using cache it may be a good idea to reset it afterwards + Rails.cache.clear + end -Two methods are provided: `take_screenshot` and `take_failed_screenshot`. -`take_failed_screenshot` is automatically included in `before_teardown` inside -Rails. + test "should show article" do + # Reuse the @article instance variable from setup + get article_url(@article) + assert_response :success + end -The `take_screenshot` helper method can be included anywhere in your tests to -take a screenshot of the browser. + test "should destroy article" do + assert_difference("Article.count", -1) do + delete article_url(@article) + end -#### Taking It Further + assert_redirected_to articles_path + end -The beauty of system testing is that it is similar to [integration testing](testing.html#integration-testing) in that it tests the user's interaction with your controller, model, and view, but -system testing is much more robust and actually tests your application as if -a real user were using it. With system tests, you can test anything that the user -themselves would do in your application such as commenting, deleting articles, -publishing draft articles, etc. + 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. + @article.reload + assert_equal "updated", @article.title + 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. Integration Testing ------------------- -Integration tests are another way of testing how various parts of our application interact. They are generally used to test important workflows within our application. +Integration tests take functional controller tests one step further, as they are focussed on testing how various parts of our application interact. They are generally used to test important workflows within our application. Rails integration tests can be created in the `test/integration` directory. -Rails integration tests can be created in the `test/integration` directory. Rails provides a generator to create an integration test skeleton for us. +Rails provides a generator to create an integration test skeleton for us. ```bash $ bin/rails generate integration_test user_flows @@ -1104,7 +1201,7 @@ We were able to successfully test a very small workflow for visiting our blog an ### Helpers Available for Integration Tests -Let's get briefly introduced to some of the helpers we can choose from in our integration tests. +Here are some of the helpers we can choose from in our integration tests. For dealing with the integration test runner, see [`ActionDispatch::Integration::Runner`](https://api.rubyonrails.org/classes/ActionDispatch/Integration/Runner.html). @@ -1114,359 +1211,264 @@ If we need to upload files, take a look at [`ActionDispatch::TestProcess::Fixtur If we need to modify the session, or state of our integration test, take a look at [`ActionDispatch::Integration::Session`](https://api.rubyonrails.org/classes/ActionDispatch/Integration/Session.html) to help. -Functional Tests for Controllers --------------------------------- - -In Rails, a focus on 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 focusing on testing how your actions handle the requests and the expected result or response. Functional controller tests are sometimes used in cases where system tests are not appropriate, e.g., to confirm an API response. - -### What to Include in Your Functional Tests - -You could 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 information displayed in the response? - -The easiest way to see functional tests in action is to generate a controller using the scaffold generator: - -```bash -$ 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 -... -``` +System Testing +-------------- -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. +Similarly to integration testing, system testing also allows you to test how the components of your app work together, but from the point of view of a user. It does this by running tests +in either a real or a headless browser (a browser which runs in the background without opening a visible window). System tests use Capybara under the hood. -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: +For creating Rails system tests, you use the `test/system` directory in your +application. Rails provides a generator to create a system test skeleton for you. ```bash -$ 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`. - -```ruby -# articles_controller_test.rb -class ArticlesControllerTest < ActionDispatch::IntegrationTest - test "should get index" do - get articles_url - assert_response :success - end -end -``` - -In the `test_should_get_index` test, Rails simulates a request on the action called `index`, making sure the request was successful -and also ensuring that 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: - -```ruby -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: - -```ruby -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: - -```ruby -post articles_path, params: { article: { title: "Ahoy!" } }, as: :json +$ bin/rails generate system_test users + invoke test_unit + create test/system/users_test.rb ``` -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. - -Let us modify `test_should_create_article` test in `articles_controller_test.rb` so that all our test pass: +Here's what a freshly generated system test looks like: ```ruby -test "should create article" do - assert_difference("Article.count") do - post articles_url, params: { article: { body: "Rails is awesome!", title: "Hello Rails" } } - end +require "application_system_test_case" - assert_redirected_to article_path(Article.last) +class UsersTest < ApplicationSystemTestCase + # test "visiting the index" do + # visit users_url + # + # assert_selector "h1", text: "Users" + # end end ``` -Now you can try running all the tests and they should pass. - -NOTE: If you followed the steps in the [Basic Authentication](getting_started.html#basic-authentication) section, you'll need to add authorization to every request header to get all the tests passing: - -```ruby -post articles_url, params: { article: { body: "Rails is awesome!", title: "Hello Rails" } }, headers: { Authorization: ActionController::HttpAuthentication::Basic.encode_credentials("dhh", "secret") } -``` - -### 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` +By default, system tests are run with the Selenium driver, using the Chrome +browser, and a screen size of 1400x1400. The next section explains how to +change the default settings. -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. +### Changing the Default Settings -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. +Rails makes changing the default settings for system tests very simple. All +the setup is abstracted away so you can focus on writing your tests. -### Testing XHR (Ajax) Requests +When you generate a new application or scaffold, an `application_system_test_case.rb` file +is created in the test directory. This is where all the configuration for your +system tests should live. -To test Ajax requests, you can specify the `xhr: true` option to `get`, `post`, -`patch`, `put`, and `delete` methods. For example: +If you want to change the default settings you can change what the system +tests are "driven by". Say you want to change the driver from Selenium to +Cuprite. First add the `cuprite` gem to your `Gemfile`. Then in your +`application_system_test_case.rb` file do the following: ```ruby -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 -end -``` - -### 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: +require "test_helper" +require "capybara/cuprite" -```ruby -flash["gordon"] # or flash[:gordon] -session["shmession"] # or session[:shmession] -cookies["are_good_for_u"] # or cookies[:are_good_for_u] +class ApplicationSystemTestCase < ActionDispatch::SystemTestCase + driven_by :cuprite +end ``` -### Instance Variables Available +The driver name is a required argument for `driven_by`. The optional arguments +that can be passed to `driven_by` are `:using` for the browser (this will only +be used by Selenium), `:screen_size` to change the size of the screen for +screenshots, and `:options` which can be used to set options supported by the +driver. -**After** a request is made, you also have access to three instance variables in your functional tests: +```ruby +require "test_helper" -* `@controller` - The controller processing the request -* `@request` - The request object -* `@response` - The response object +class ApplicationSystemTestCase < ActionDispatch::SystemTestCase + driven_by :selenium, using: :firefox +end +``` +If you want to use a headless browser, you could use Headless Chrome or Headless Firefox by adding +`headless_chrome` or `headless_firefox` in the `:using` argument. ```ruby -class ArticlesControllerTest < ActionDispatch::IntegrationTest - test "should get index" do - get articles_url +require "test_helper" - assert_equal "index", @controller.action_name - assert_equal "application/x-www-form-urlencoded", @request.media_type - assert_match "Articles", @response.body - end +class ApplicationSystemTestCase < ActionDispatch::SystemTestCase + driven_by :selenium, using: :headless_chrome end ``` -### Setting Headers and CGI Variables - -[HTTP headers](https://datatracker.ietf.org/doc/html/rfc2616#section-5.3) -and -[CGI variables](https://datatracker.ietf.org/doc/html/rfc3875#section-4.1) -can be passed as headers: +If you want to use a remote browser, e.g. +[Headless Chrome in Docker](https://github.com/SeleniumHQ/docker-selenium), +you have to add a remote `url` and set `browser` as remote through `options`. ```ruby -# setting an HTTP Header -get articles_url, headers: { "Content-Type": "text/plain" } # simulate the request with custom header +require "test_helper" -# setting a CGI variable -get articles_url, headers: { "HTTP_REFERER": "http://example.com/home" } # simulate the request with custom env variable +class ApplicationSystemTestCase < ActionDispatch::SystemTestCase + url = ENV.fetch("SELENIUM_REMOTE_URL", nil) + options = if url + { browser: :remote, url: url } + else + { browser: :chrome } + end + driven_by :selenium, using: :headless_chrome, options: options +end ``` -### Testing `flash` Notices - -If you remember from earlier, one of the Three Hashes of the Apocalypse was `flash`. +Now you should get a connection to the remote browser. -We want to add a `flash` message to our blog application whenever someone -successfully creates a new Article. +```bash +$ SELENIUM_REMOTE_URL=http://localhost:4444/wd/hub bin/rails test:system +``` -Let's start by adding this assertion to our `test_should_create_article` test: +If your application in test is running remote too, e.g. within a Docker container, +Capybara needs more input about how to +[call remote servers](https://github.com/teamcapybara/capybara#calling-remote-servers). ```ruby -test "should create article" do - assert_difference("Article.count") do - post articles_url, params: { article: { title: "Some title" } } - end +require "test_helper" - assert_redirected_to article_path(Article.last) - assert_equal "Article was successfully created.", flash[:notice] +class ApplicationSystemTestCase < ActionDispatch::SystemTestCase + def setup + Capybara.server_host = "0.0.0.0" # bind to all interfaces + Capybara.app_host = "http://#{IPSocket.getaddress(Socket.gethostname)}" if ENV["SELENIUM_REMOTE_URL"].present? + super + end + # ... end ``` -If we run our test now, we should see a failure: +Now you should get a connection to a remote browser and server, regardless if it +is running in a Docker container or CI. -```bash -$ bin/rails test test/controllers/articles_controller_test.rb -n test_should_create_article -Run options: -n test_should_create_article --seed 32266 +If your Capybara configuration requires more setup than provided by Rails, this +additional configuration could be added into the `application_system_test_case.rb` +file. -# Running: +Please see [Capybara's documentation](https://github.com/teamcapybara/capybara#setup) +for additional settings. -F +### Implementing a System Test -Finished in 0.114870s, 8.7055 runs/s, 34.8220 assertions/s. +Now we're going to add a system test to our blog application. We'll demonstrate +writing a system test by visiting the index page and creating a new blog article. - 1) Failure: -ArticlesControllerTest#test_should_create_article [/test/controllers/articles_controller_test.rb:16]: ---- expected -+++ actual -@@ -1 +1 @@ --"Article was successfully created." -+nil +If you used the scaffold generator, a system test skeleton was automatically +created for you. If you didn't use the scaffold generator, start by creating a +system test skeleton. -1 runs, 4 assertions, 1 failures, 0 errors, 0 skips +```bash +$ bin/rails generate system_test articles ``` -Let's implement the flash message now in our controller. Our `:create` action should now look like this: +It should have created a test file placeholder for us. With the output of the +previous command you should see: + +``` + invoke test_unit + create test/system/articles_test.rb +``` + +Now let's open that file and write our first assertion: ```ruby -def create - @article = Article.new(article_params) +require "application_system_test_case" - if @article.save - flash[:notice] = "Article was successfully created." - redirect_to @article - else - render "new" +class ArticlesTest < ApplicationSystemTestCase + test "viewing the index" do + visit articles_path + assert_selector "h1", text: "Articles" end end ``` -Now if we run our tests, we should see it pass: - -```bash -$ bin/rails test test/controllers/articles_controller_test.rb -n test_should_create_article -Run options: -n test_should_create_article --seed 18981 - -# Running: - -. +The test should see that there is an `h1` on the articles index page and pass. -Finished in 0.081972s, 12.1993 runs/s, 48.7972 assertions/s. +Run the system tests. -1 runs, 4 assertions, 0 failures, 0 errors, 0 skips +```bash +$ bin/rails test:system ``` -### Putting It Together +NOTE: By default, running `bin/rails test` won't run your system tests. +Make sure to run `bin/rails test:system` to actually run them. +You can also run `bin/rails test:all` to run all tests, including system tests. -At this point our Articles controller tests the `:index` as well as `:new` and `:create` actions. What about dealing with existing data? +#### Creating Articles System Test -Let's write a test for the `:show` action: +Now let's test the flow for creating a new article in our blog. ```ruby -test "should show article" do - article = articles(:one) - get article_url(article) - assert_response :success -end -``` +test "should create Article" do + visit articles_path -Remember from our discussion earlier on fixtures, the `articles()` method will give us access to our Articles fixtures. + click_on "New Article" -How about deleting an existing Article? + fill_in "Title", with: "Creating an Article" + fill_in "Body", with: "Created this article successfully!" -```ruby -test "should destroy article" do - article = articles(:one) - assert_difference("Article.count", -1) do - delete article_url(article) - end + click_on "Create Article" - assert_redirected_to articles_path + assert_text "Creating an Article" end ``` -We can also add a test for updating an existing Article. +The first step is to call `visit articles_path`. This will take the test to the +articles index page. -```ruby -test "should update article" do - article = articles(:one) +Then the `click_on "New Article"` will find the "New Article" button on the +index page. This will redirect the browser to `/articles/new`. - patch article_url(article), params: { article: { title: "updated" } } +Then the test will fill in the title and body of the article with the specified +text. Once the fields are filled in, "Create Article" is clicked on which will +send a POST request to create the new article in the database. - assert_redirected_to article_path(article) - # Reload association to fetch updated data and assert that title is updated. - article.reload - assert_equal "updated", article.title -end -``` +We will be redirected back to the articles index page and there we assert +that the text from the new article's title is on the articles index page. -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`. +#### Testing for Multiple Screen Sizes -Our test should now look something as what follows. Disregard the other tests for now, we're leaving them out for brevity. +If you want to test for mobile sizes on top of testing for desktop, +you can create another class that inherits from `ActionDispatch::SystemTestCase` and use it in your +test suite. In this example a file called `mobile_system_test_case.rb` is created +in the `/test` directory with the following configuration. ```ruby require "test_helper" -class ArticlesControllerTest < ActionDispatch::IntegrationTest - # called before every single test - setup do - @article = articles(:one) - end +class MobileSystemTestCase < ActionDispatch::SystemTestCase + driven_by :selenium, using: :chrome, screen_size: [375, 667] +end +``` - # called after every single test - teardown do - # when controller is using cache it may be a good idea to reset it afterwards - Rails.cache.clear - end +To use this configuration, create a test inside `test/system` that inherits from `MobileSystemTestCase`. +Now you can test your app using multiple different configurations. - test "should show article" do - # Reuse the @article instance variable from setup - get article_url(@article) - assert_response :success +```ruby +require "mobile_system_test_case" + +class PostsTest < MobileSystemTestCase + test "visiting the index" do + visit posts_url + assert_selector "h1", text: "Posts" end +end +``` +#### Screenshot Helper - test "should destroy article" do - assert_difference("Article.count", -1) do - delete article_url(@article) - end +The [`ScreenshotHelper`](https://api.rubyonrails.org/v5.1.7/classes/ActionDispatch/SystemTesting/TestHelpers/ScreenshotHelper.html) is a helper designed to capture screenshots of your tests. +This can be helpful for viewing the browser at the point a test failed, or +to view screenshots later for debugging. - assert_redirected_to articles_path - end +Two methods are provided: `take_screenshot` and `take_failed_screenshot`. +`take_failed_screenshot` is automatically included in `before_teardown` inside +Rails. - test "should update article" do - patch article_url(@article), params: { article: { title: "updated" } } +The `take_screenshot` helper method can be included anywhere in your tests to +take a screenshot of the browser. - assert_redirected_to article_path(@article) - # Reload association to fetch updated data and assert that title is updated. - @article.reload - assert_equal "updated", @article.title - end -end -``` +#### Taking It Further -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. +The beauty of system testing is that it is similar to [integration testing](testing.html#integration-testing) in that it tests the user's interaction with your controller, model, and view, but +system testing is much more robust and actually tests your application as if +a real user were using it. With system tests, you can test anything that the user +themselves would do in your application such as commenting, deleting articles, +publishing draft articles, etc. Test Helpers ------------ From 3d2c6de7f8bf4f7ab5ac05db7f6aee80ff57bf16 Mon Sep 17 00:00:00 2001 From: harriet oughton Date: Wed, 9 Oct 2024 18:22:09 +0100 Subject: [PATCH 11/31] Add update to test changes and add note about fixtures in test scaffold code --- guides/source/testing.md | 29 ++++++++++++++++++----------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/guides/source/testing.md b/guides/source/testing.md index faea104f2679b..b14dc2a40982f 100644 --- a/guides/source/testing.md +++ b/guides/source/testing.md @@ -780,6 +780,10 @@ create test/controllers/articles_controller_test.rb ... ``` +NOTE: if you are generating test scaffold code, you will see an `@article` value is set and used throughout the test file. +This instance of `article` uses the attributes nested within a `:one` key in the `test/fixtures/articles.yml` file. Make sure you have set the key and related values before you try to +run the tests. + Let's take a look at one such test, `test_should_get_index` from the file `articles_controller_test.rb`. ```ruby @@ -829,7 +833,7 @@ post articles_path, params: { article: { title: "Ahoy!" } }, as: :json NOTE: If you try running the `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 the `test_should_create_article` test in `articles_controller_test.rb` so that all our tests pass: +Let us modify the `test_should_create_article` test in `articles_controller_test.rb` so that this test passes: ```ruby test "should create article" do @@ -841,7 +845,7 @@ test "should create article" do end ``` -Now you can try running all the tests and they should pass. +You can now run this test and it will pass. NOTE: If you followed the steps in the [Basic Authentication](getting_started.html#basic-authentication) section, you'll need to add authorization to every request header to get all the tests passing: @@ -895,7 +899,7 @@ session["shmession"] # or session[:shmession] cookies["are_good_for_u"] # or cookies[:are_good_for_u] ``` -### Instance Variables Available +### Instance Variables You also have access to three instance variables in your functional tests after a request is made: @@ -918,7 +922,7 @@ end ### Setting Headers and CGI Variables -HTTP headers are pieces of information sent along with HTTP requests to provide important metadata along with that request. +HTTP headers are pieces of information sent along with HTTP requests to provide important metadata. CGI variables are environment variables used to exchange information between the web server and the application. HTTP headers and CGI variables can be tested by being passed as headers: @@ -1006,11 +1010,14 @@ Finished in 0.081972s, 12.1993 runs/s, 48.7972 assertions/s. 1 runs, 4 assertions, 0 failures, 0 errors, 0 skips ``` +NOTE: If you generated your controller using the scaffold generator, the flash message will already be +implemented in your `create` action. + ### 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? +At this point we have looked at tests for the `:index` as well as the`:create` action. What about dealing with existing data? -Let's write a test for the `:show` action: +Let's make sure we have a test for the `:show` action: ```ruby test "should show article" do @@ -1020,7 +1027,7 @@ test "should show article" do end ``` -Remember from our discussion earlier on fixtures, the `articles()` method will give us access to our Articles fixtures. +If you remember from our discussion earlier on fixtures, the `articles()` method will give us access to our Articles fixtures. How about deleting an existing Article? @@ -1035,7 +1042,7 @@ test "should destroy article" do end ``` -We can also add a test for updating an existing Article. +We can also consider a test for updating an existing Article. ```ruby test "should update article" do @@ -1050,9 +1057,9 @@ test "should update article" do 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`. +Notice we're starting to see some duplication in these three tests, they both access the same Article fixture data. It is possible to D.R.Y. this up ('Don't Repeat Yourself') by using the `setup` and `teardown` methods provided by `ActiveSupport::Callbacks`. -Our test should now look something like the below. Disregard the other tests for now, we're leaving them out for brevity. +Our tests now might look something like the below. ```ruby require "test_helper" @@ -1094,7 +1101,7 @@ class ArticlesControllerTest < ActionDispatch::IntegrationTest 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. +NOTE: 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. Integration Testing ------------------- From c91fe9a59c1a21723020560c0c285a568cb177d3 Mon Sep 17 00:00:00 2001 From: harriet oughton Date: Wed, 9 Oct 2024 19:20:14 +0100 Subject: [PATCH 12/31] Tweak wording --- guides/source/testing.md | 179 +++++++++++++++++++-------------------- 1 file changed, 87 insertions(+), 92 deletions(-) diff --git a/guides/source/testing.md b/guides/source/testing.md index b14dc2a40982f..faa305a21114f 100644 --- a/guides/source/testing.md +++ b/guides/source/testing.md @@ -1534,7 +1534,7 @@ require "test_helpers/multiple_assertions" class NumberTest < ActiveSupport::TestCase include MultipleAssertions - test "420 is a multiple of forty two" do + test "420 is a multiple of 42" do assert_multiple_of_forty_two 420 end end @@ -1574,99 +1574,49 @@ For more information on routing assertions available in Rails, see the API docum Testing Views ------------- -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. +Testing the response to your request by asserting the presence of key HTML elements and their content is one way to test the views of your application. Like route tests, view tests reside in `test/controllers/` or are part of controller tests. -There are two forms of `assert_select`: +Methods like `assert_dom` and `assert_dom_equal` allow you to query HTML elements of the response by using a simple yet powerful syntax. -`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. - -`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. - -For example, you could verify the contents on the title element in your response with: +`assert_dom` is an assertion that will return true if matching elements are found. For example, you could verify that the page title is "Welcome to the Rails Testing Guide" as follows: ```ruby -assert_select "title", "Welcome to Rails Testing Guide" +assert_dom "title", "Welcome to the Rails Testing Guide" ``` -You can also use nested `assert_select` blocks for deeper investigation. +You can also use nested `assert_dom` blocks for deeper investigation. -In the following example, the inner `assert_select` for `li.menu_item` runs +In the following example, the inner `assert_dom` for `li.menu_item` runs within the collection of elements selected by the outer block: ```ruby -assert_select "ul.navigation" do - assert_select "li.menu_item" +assert_dom "ul.navigation" do + assert_dom "li.menu_item" end ``` -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. +A collection of selected elements may also be iterated through so that `assert_dom` 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. ```ruby -assert_select "ol" do |elements| +assert_dom "ol" do |elements| elements.each do |element| - assert_select element, "li", 4 + assert_dom element, "li", 4 end end -assert_select "ol" do - assert_select "li", 8 +assert_dom "ol" do + assert_dom "li", 8 end ``` -This assertion is quite powerful. For more advanced usage, refer to its [documentation](https://github.com/rails/rails-dom-testing/blob/main/lib/rails/dom/testing/assertions/selector_assertions.rb). - -### Additional View-Based Assertions - -There are more assertions that are primarily used in testing views: - -| Assertion | Purpose | -| --------------------------------------------------------- | ------- | -| `assert_select_email` | Allows you to make assertions on the body of an e-mail. | -| `assert_select_encoded` | Allows you to make assertions on encoded HTML. It does this by un-encoding the contents of each element and then calling the block with all the un-encoded elements.| -| `css_select(selector)` or `css_select(element, selector)` | Returns an array of all the elements selected by the _selector_. In the second variant it first matches the base _element_ and tries to match the _selector_ expression on any of its children. If there are no matches both variants return an empty array.| - -Here's an example of using `assert_select_email`: +The `assert_dom_equal` method tests two HTML strings for equivalency, as in the example below: ```ruby -assert_select_email do - assert_select "small", "Please click the 'Unsubscribe' link if you want to opt-out." -end +assert_dom_equal 'Read more', + link_to("Read more", "http://www.further-reading.com") ``` -### Testing View Partials - -Partial templates - usually called "partials" - are another device for breaking the rendering process into more manageable chunks. With partials, you can extract pieces of code from your templates to separate files and reuse them throughout your templates. - -View tests provide an opportunity to test that partials render content the way you expect. View partial tests reside in `test/views/` and inherit from `ActionView::TestCase`. - -To render a partial, call `render` like you would in a template. The content is -available through the test-local `#rendered` method: - -```ruby -class ArticlePartialTest < ActionView::TestCase - test "renders a link to itself" do - article = Article.create! title: "Hello, world" - - render "articles/article", article: article - - assert_includes rendered, article.title - end -end -``` - -Tests that inherit from `ActionView::TestCase` also have access to [`assert_select`](#testing-views) and the [other additional view-based assertions](#additional-view-based-assertions) provided by [rails-dom-testing][]: - -```ruby -test "renders a link to itself" do - article = Article.create! title: "Hello, world" - - render "articles/article", article: article - - assert_select "a[href=?]", article_url(article), text: article.title -end -``` +These assertions are quite powerful. For more advanced usage, refer to their [documentation](https://github.com/rails/rails-dom-testing). In order to integrate with [rails-dom-testing][], tests that inherit from `ActionView::TestCase` declare a `document_root_element` method that returns the @@ -1784,6 +1734,57 @@ end [rails-dom-testing]: https://github.com/rails/rails-dom-testing [RSS content]: https://www.rssboard.org/rss-specification +### Additional View-Based Assertions + +There are more assertions that are primarily used in testing views: + +| Assertion | Purpose | +| --------------------------------------------------------- | ------- | +| `assert_dom_email` | Allows you to make assertions on the body of an e-mail. | +| `assert_dom_encoded` | Allows you to make assertions on encoded HTML. It does this by un-encoding the contents of each element and then calling the block with all the un-encoded elements.| +| `css_select(selector)` or `css_select(element, selector)` | Returns an array of all the elements selected by the _selector_. In the second variant it first matches the base _element_ and tries to match the _selector_ expression on any of its children. If there are no matches both variants return an empty array.| + +Here's an example of using `assert_dom_email`: + +```ruby +assert_dom_email do + assert_dom "small", "Please click the 'Unsubscribe' link if you want to opt-out." +end +``` + +### Testing View Partials + +[Partial](layouts_and_rendering.html#using-partials) templates - usually called "partials" - are another device for breaking the rendering process into more manageable chunks. With partials, you can extract pieces of code from your templates to separate files and reuse them throughout your templates. + +View tests provide an opportunity to test that partials render content the way you expect. View partial tests can be stored in `test/views/` and inherit from `ActionView::TestCase`. + +To render a partial, call `render` like you would in a template. The content is +available through the test-local `rendered` method: + +```ruby +class ArticlePartialTest < ActionView::TestCase + test "renders a link to itself" do + article = Article.create! title: "Hello, world" + + render "articles/article", article: article + + assert_includes rendered, article.title + end +end +``` + +Tests that inherit from `ActionView::TestCase` also have access to [`assert_dom`](#testing-views) and the [other additional view-based assertions](#additional-view-based-assertions) provided by [rails-dom-testing][]: + +```ruby +test "renders a link to itself" do + article = Article.create! title: "Hello, world" + + render "articles/article", article: article + + assert_dom "a[href=?]", article_url(article), text: article.title +end +``` + ### Testing View Helpers A helper is just a simple module where you can define methods which are @@ -1821,10 +1822,6 @@ access to Rails' helper methods such as `link_to` or `pluralize`. Testing Mailers -------------------- -Testing mailer classes requires some specific tools to do a thorough job. - -### 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: @@ -1835,13 +1832,13 @@ The goals of testing your mailer classes are to ensure that: #### 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. +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](testing.html#fixtures)). In the functional tests you don't so much test the 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 +#### Mailer 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. @@ -1888,13 +1885,15 @@ You have been invited. Cheers! ``` -This is the right time to understand a little more about writing tests for your mailers. The line `ActionMailer::Base.delivery_method = :test` in `config/environments/test.rb` sets the delivery method to test mode so that email will not actually be delivered (useful to avoid spamming your users while testing) but instead it will be appended to an array (`ActionMailer::Base.deliveries`). +#### Configuring the Delivery Method for Test + +The line `ActionMailer::Base.delivery_method = :test` in `config/environments/test.rb` sets the delivery method to test mode so that the email will not actually be delivered (useful to avoid spamming your users while testing). Instead, the email will be appended to an array (`ActionMailer::Base.deliveries`). NOTE: 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` #### Testing Enqueued Emails -You can use the `assert_enqueued_email_with` assertion to confirm that the email has been enqueued with all of the expected mailer method arguments and/or parameterized mailer parameters. This allows you to match any email that have been enqueued with the `deliver_later` method. +You can use the `assert_enqueued_email_with` assertion to confirm that the email has been enqueued with all of the expected mailer method arguments and/or parameterized mailer parameters. This allows you to match any emails that have been enqueued with the `deliver_later` method. As with the basic test case, we create the email and store the returned object in the `email` variable. The following examples include variations of passing arguments and/or parameters. @@ -1927,8 +1926,8 @@ class UserMailerTest < ActionMailer::TestCase email = UserMailer.create_invite(from: "me@example.com", to: "friend@example.com") # Test that the email got enqueued with the correct named arguments - assert_enqueued_email_with UserMailer, :create_invite, args: [{ from: "me@example.com", - to: "friend@example.com" }] do + assert_enqueued_email_with UserMailer, :create_invite, + args: [{ from: "me@example.com", to: "friend@example.com" }] do email.deliver_later end end @@ -1946,8 +1945,8 @@ class UserMailerTest < ActionMailer::TestCase email = UserMailer.with(all: "good").create_invite("me@example.com", "friend@example.com") # Test that the email got enqueued with the correct mailer parameters and arguments - assert_enqueued_email_with UserMailer, :create_invite, params: { all: "good" }, - args: ["me@example.com", "friend@example.com"] do + assert_enqueued_email_with UserMailer, :create_invite, + params: { all: "good" }, args: ["me@example.com", "friend@example.com"] do email.deliver_later end end @@ -2020,7 +2019,7 @@ Jobs can be tested in isolation (focusing on the job's behavior) and in context When you generate a job, an associated test file will also be generated in the `test/jobs` directory. -Here is an example test for a billing job: +Here is a test you could write for a billing job: ```ruby require "test_helper" @@ -2235,6 +2234,8 @@ end Running tests in Continuous Integration (CI) -------------------------------------------- +Continuous Integration (CI) is a development practice where changes are frequently integrated into the main codebase, and as such, are automatically tested before merge. + To run all tests in a CI environment, there's just one command you need: ```bash @@ -2242,7 +2243,7 @@ $ bin/rails test ``` If you are using [System Tests](#system-testing), `bin/rails test` will not run them, since -they can be slow. To also run them, add an another CI step that runs `bin/rails test:system`, +they can be slow. To also run them, add another CI step that runs `bin/rails test:system`, or change your first step to `bin/rails test:all`, which runs all tests including system tests. Parallel Testing @@ -2319,13 +2320,7 @@ end Rails applications generated from JRuby or TruffleRuby will automatically include the `with: :threads` option. -The number of workers passed to `parallelize` determines the number of threads the tests will use. You may -want to parallelize your local test suite differently from your CI, so an environment variable is provided -to be able to easily change the number of workers a test run should use: - -```bash -$ PARALLEL_WORKERS=15 bin/rails test -``` +NOTE: As in the section above, you can also use the environment variable `PARALLEL_WORKERS` in this context, to be able to change the number of workers your test run should use. ### Testing Parallel Transactions @@ -2374,13 +2369,13 @@ Testing Eager Loading Normally, applications do not eager load in the `development` or `test` environments to speed things up. But they do in the `production` environment. -If some file in the project cannot be loaded for whatever reason, you better detect it before deploying to production, right? +If some file in the project cannot be loaded for whatever reason, it is important to detect it before deploying to production. ### Continuous Integration If your project has CI in place, eager loading in CI is an easy way to ensure the application eager loads. -CIs typically set some environment variable to indicate the test suite is running there. For example, it could be `CI`: +CIs typically set an environment variable to indicate the test suite is running there. For example, it could be `CI`: ```ruby # config/environments/test.rb @@ -2422,7 +2417,7 @@ Additional Testing Resources ### Errors -In system tests, integration tests and functional controller tests, Rails will attempt to rescue from exceptions raised and respond with HTML error pages by default. This behavior can be controlled by the [`config.action_dispatch.show_exceptions`](/configuring.html#config-action-dispatch-show-exceptions) configuration. +In system tests, integration tests and functional controller tests, Rails will attempt to rescue from errors raised and respond with HTML error pages by default. This behavior can be controlled by the [`config.action_dispatch.show_exceptions`](/configuring.html#config-action-dispatch-show-exceptions) configuration. ### Testing Time-Dependent Code From 50e1f074bce48c4815b7b62602b0323f0c10d7d1 Mon Sep 17 00:00:00 2001 From: harriet oughton Date: Fri, 25 Oct 2024 18:44:31 +0100 Subject: [PATCH 13/31] Apply final changes during proof-read --- guides/source/testing.md | 982 ++++++++++++++++++++++++++------------- 1 file changed, 662 insertions(+), 320 deletions(-) diff --git a/guides/source/testing.md b/guides/source/testing.md index faa305a21114f..e402015c3d6b9 100644 --- a/guides/source/testing.md +++ b/guides/source/testing.md @@ -8,7 +8,8 @@ This guide covers built-in mechanisms in Rails for testing your application. After reading this guide, you will know: * Rails testing terminology. -* How to write unit, functional, integration, and system tests for your application. +* How to write unit, functional, integration, and system tests for your + application. * Other popular testing approaches and plugins. -------------------------------------------------------------------------------- @@ -16,20 +17,26 @@ After reading this guide, you will know: Why Write Tests? ---------------- -Rails makes it super easy to write your tests. It starts by producing skeleton test code while you are creating your models and controllers. +Rails makes it super easy to write your tests. It starts by producing skeleton +test code when you create your models and controllers. -By running your Rails tests you can ensure your code adheres to the desired functionality even after some major code refactoring. +By running your Rails tests you can quickly and easily ensure your code still +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 view the output through your browser. +Rails tests can also simulate browser requests and thus you can test your +application's response without having to view the output through your browser. Introduction to Testing ----------------------- -Testing wasn't just an afterthought - it was woven into the Rails fabric from the very beginning. +Testing was woven into the Rails fabric from the very beginning, and is central +to the development process right from the creation of a new application. ### Test Setup -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: +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: ```bash $ ls -F test @@ -39,35 +46,46 @@ channels/ fixtures/ integration/ ### Test Directories -The `helpers`, `mailers`, and `models` directories are where tests for view helpers, mailers, and models respectively should be stored. The `channels` directory is where tests for Action Cable connection and channels should be stored. The `controllers` directory is where tests for controllers, routes, and views should be stored. The `integration` directory is where tests for interactions between controllers should be stored. +The `helpers`, `mailers`, and `models` directories are where tests for view +helpers, mailers, and models respectively should be stored. The `channels` +directory is where tests for Action Cable connection and channels should be +stored. The `controllers` directory is where tests for controllers, routes, and +views should be stored. The `integration` directory is where tests for +interactions between controllers should be stored. 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. +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 can be stored in the `fixtures` directory. +Fixtures are a way of organizing test data; they can be stored in the `fixtures` +directory. -A `jobs` directory will also be created when an associated test is first generated. +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. +The `application_system_test_case.rb` holds the default configuration for your +system tests. ### The Test Environment -By default, every Rails application has three environments: development, test, and production. +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`. +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`. NOTE: Your tests are run under `RAILS_ENV=test`. ### Rails Meets Minitest -We introduced the `bin/rails generate model` command in the -[Getting Started with Rails](getting_started.html#mvc-and-you-generating-a-model) guide. Alongside creating a model, this command also creates a test stub in the `test` directory: +We introduced the `bin/rails generate model` command in the [Getting Started +with Rails](getting_started.html#mvc-and-you-generating-a-model) guide. +Alongside creating a model, this command also creates a test stub in the `test` +directory: ```bash $ bin/rails generate model article title:string body:text @@ -89,13 +107,16 @@ class ArticleTest < ActiveSupport::TestCase end ``` -A line by line examination of this file will help get you oriented to Rails testing code and terminology. +A line by line examination of this file will help get you oriented to Rails +testing code and terminology. ```ruby 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. +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. ```ruby class ArticleTest < ActiveSupport::TestCase @@ -103,12 +124,19 @@ class ArticleTest < ActiveSupport::TestCase end ``` -This is called a test case, because the `ArticleTest` class inherits from `ActiveSupport::TestCase`. It therefore also has all the methods from `ActiveSupport::TestCase` available to it. Later in this guide, we'll see some of the methods this gives us. +This is called a test case, because the `ArticleTest` class inherits from +`ActiveSupport::TestCase`. It therefore also has all the methods from +`ActiveSupport::TestCase` available to it. Later in this guide, we'll see some +of the methods this 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. +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 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: +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: ```ruby test "the truth" do @@ -124,9 +152,14 @@ def test_the_truth end ``` -Although you can still use regular method definitions, using the `test` macro allows for a more readable test name. +Although you can still use regular method definitions, using the `test` macro +allows for a more readable test name. -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. +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: @@ -134,18 +167,23 @@ 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: +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? +* does this value equal 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. +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. #### 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. Here were are asserting that the article will not save, which will fail the test when the article saves successfully. +To see how a test failure is reported, you can add a failing test to the +`article_test.rb` test case. Here, we are asserting that the article will not +save, which will fail the test when the article saves successfully. ```ruby test "should not save article without title" do @@ -154,7 +192,8 @@ test "should not save article without title" do end ``` -Let us run this newly added test (where `6` is the line number where the test is defined). +Let us run this newly added test (where `6` is the line number where the test is +defined). ```bash $ bin/rails test test/models/article_test.rb:6 @@ -179,7 +218,13 @@ 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: +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: ```ruby test "should not save article without title" do @@ -196,7 +241,8 @@ ArticleTest#test_should_not_save_article_without_title [/path/to/blog/test/model Saved the article without a title ``` -To get this test to pass we can add a model level validation for the `title` field. +To get this test to pass we can add a model level validation for the `title` +field. ```ruby class Article < ApplicationRecord @@ -204,7 +250,9 @@ class Article < ApplicationRecord end ``` -Now the test should pass, as we have not initialized the article in our test with a `title`, so the model validation will prevent the save. Let us verify by running the test again: +Now the test should pass, as we have not initialized the article in our test +with a `title`, so the model validation will prevent the save. Let us verify by +running the test again: ```bash $ bin/rails test test/models/article_test.rb:6 @@ -265,24 +313,27 @@ 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 green dot above the 'finished' line denotes the one passing test. +Notice the 'E' in the output. It denotes a test with error. The green dot above +the 'finished' line denotes the one passing test. NOTE: The execution of each test method stops as soon as any error or an assertion failure is encountered, and the test suite continues with the next method. All test methods are executed in random order. The -[`config.active_support.test_order`][] option can be used to configure test order. +[`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: +code. However there are situations when you want to see the full backtrace. Set +the `-b` (or `--backtrace`) argument to enable this behavior: ```bash $ bin/rails test -b test/models/article_test.rb ``` -If we want this test to pass we can modify it to use `assert_raises` (so we are now checking for the presence of the error) like so: +If we want this test to pass we can modify it to use `assert_raises` (so we are +now checking for the presence of the error) like so: ```ruby test "should report error" do @@ -295,11 +346,14 @@ end This test should now pass. -[`config.active_support.test_order`]: configuring.html#config-active-support-test-order +[`config.active_support.test_order`]: + configuring.html#config-active-support-test-order ### Minitest 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. +By now you've caught a glimpse of some of the assertions that are available. +Assertions are the worker bees of testing. They are the ones that actually +perform the checks to ensure that things are going as planned. Here's an extract of the assertions you can use with [`Minitest`](https://github.com/minitest/minitest), the default testing library @@ -343,13 +397,16 @@ specify to make your test failure messages clearer. | `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 the -[Minitest API documentation](http://docs.seattlerb.org/minitest/Minitest), specifically +more up-to-date list, please check the [Minitest API +documentation](http://docs.seattlerb.org/minitest/Minitest), specifically [`Minitest::Assertions`](http://docs.seattlerb.org/minitest/Minitest/Assertions.html). -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. +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. +NOTE: Creating your own assertions is an advanced topic that we won't cover in +this guide. ### Rails-Specific Assertions @@ -372,26 +429,44 @@ Rails adds some custom assertions of its own to the `minitest` framework: | [`assert_queries_match(pattern, count: nil, include_schema: false, &block)`][] | Asserts that `&block` generates SQL queries that match the pattern.| | [`assert_no_queries_match(pattern, &block)`][] | Asserts that `&block` generates no SQL queries that match the pattern.| -[`assert_difference(expressions, difference = 1, message = nil) {...}`]: https://api.rubyonrails.org/classes/ActiveSupport/Testing/Assertions.html#method-i-assert_difference) -[`assert_no_difference(expressions, message = nil, &block)`]: https://api.rubyonrails.org/classes/ActiveSupport/Testing/Assertions.html#method-i-assert_no_difference -[`assert_changes(expressions, message = nil, from:, to:, &block)`]: https://api.rubyonrails.org/classes/ActiveSupport/Testing/Assertions.html#method-i-assert_changes -[`assert_no_changes(expressions, message = nil, &block)`]: https://api.rubyonrails.org/classes/ActiveSupport/Testing/Assertions.html#method-i-assert_no_changes -[`assert_nothing_raised { block }`]: https://api.rubyonrails.org/classes/ActiveSupport/Testing/Assertions.html#method-i-assert_nothing_raised -[`assert_recognizes(expected_options, path, extras={}, message=nil)`]: https://api.rubyonrails.org/classes/ActionDispatch/Assertions/RoutingAssertions.html#method-i-assert_recognizes -[`assert_generates(expected_path, options, defaults={}, extras = {}, message=nil)`]: https://api.rubyonrails.org/classes/ActionDispatch/Assertions/RoutingAssertions.html#method-i-assert_generates -[`assert_routing(expected_path, options, defaults={}, extras = {}, message=nil)`]: https://api.rubyonrails.org/classes/ActionDispatch/Assertions/RoutingAssertions.html#method-i-assert_routing -[`assert_response(type, message = nil)`]: https://api.rubyonrails.org/classes/ActionDispatch/Assertions/ResponseAssertions.html#method-i-assert_response -[`assert_redirected_to(options = {}, message=nil)`]: https://api.rubyonrails.org/classes/ActionDispatch/Assertions/ResponseAssertions.html#method-i-assert_redirected_to -[`assert_queries_count(count = nil, include_schema: false, &block)`]: https://api.rubyonrails.org/classes/ActiveRecord/Assertions/QueryAssertions.html#method-i-assert_queries_count -[`assert_no_queries(include_schema: false, &block)`]: https://api.rubyonrails.org/classes/ActiveRecord/Assertions/QueryAssertions.html#method-i-assert_no_queries -[`assert_queries_match(pattern, count: nil, include_schema: false, &block)`]: https://api.rubyonrails.org/classes/ActiveRecord/Assertions/QueryAssertions.html#method-i-assert_queries_match -[`assert_no_queries_match(pattern, &block)`]: https://api.rubyonrails.org/classes/ActiveRecord/Assertions/QueryAssertions.html#method-i-assert_no_queries_match +[`assert_difference(expressions, difference = 1, message = nil) {...}`]: + https://api.rubyonrails.org/classes/ActiveSupport/Testing/Assertions.html#method-i-assert_difference) +[`assert_no_difference(expressions, message = nil, &block)`]: + https://api.rubyonrails.org/classes/ActiveSupport/Testing/Assertions.html#method-i-assert_no_difference +[`assert_changes(expressions, message = nil, from:, to:, &block)`]: + https://api.rubyonrails.org/classes/ActiveSupport/Testing/Assertions.html#method-i-assert_changes +[`assert_no_changes(expressions, message = nil, &block)`]: + https://api.rubyonrails.org/classes/ActiveSupport/Testing/Assertions.html#method-i-assert_no_changes +[`assert_nothing_raised { block }`]: + https://api.rubyonrails.org/classes/ActiveSupport/Testing/Assertions.html#method-i-assert_nothing_raised +[`assert_recognizes(expected_options, path, extras={}, message=nil)`]: + https://api.rubyonrails.org/classes/ActionDispatch/Assertions/RoutingAssertions.html#method-i-assert_recognizes +[`assert_generates(expected_path, options, defaults={}, extras = {}, + message=nil)`]: + https://api.rubyonrails.org/classes/ActionDispatch/Assertions/RoutingAssertions.html#method-i-assert_generates +[`assert_routing(expected_path, options, defaults={}, extras = {}, + message=nil)`]: + https://api.rubyonrails.org/classes/ActionDispatch/Assertions/RoutingAssertions.html#method-i-assert_routing +[`assert_response(type, message = nil)`]: + https://api.rubyonrails.org/classes/ActionDispatch/Assertions/ResponseAssertions.html#method-i-assert_response +[`assert_redirected_to(options = {}, message=nil)`]: + https://api.rubyonrails.org/classes/ActionDispatch/Assertions/ResponseAssertions.html#method-i-assert_redirected_to +[`assert_queries_count(count = nil, include_schema: false, &block)`]: + https://api.rubyonrails.org/classes/ActiveRecord/Assertions/QueryAssertions.html#method-i-assert_queries_count +[`assert_no_queries(include_schema: false, &block)`]: + https://api.rubyonrails.org/classes/ActiveRecord/Assertions/QueryAssertions.html#method-i-assert_no_queries +[`assert_queries_match(pattern, count: nil, include_schema: false, &block)`]: + https://api.rubyonrails.org/classes/ActiveRecord/Assertions/QueryAssertions.html#method-i-assert_queries_match +[`assert_no_queries_match(pattern, &block)`]: + https://api.rubyonrails.org/classes/ActiveRecord/Assertions/QueryAssertions.html#method-i-assert_no_queries_match You'll see the usage of some of these assertions in the next chapter. ### Assertions in Our 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: +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`](https://api.rubyonrails.org/classes/ActiveSupport/TestCase.html) * [`ActionMailer::TestCase`](https://api.rubyonrails.org/classes/ActionMailer/TestCase.html) @@ -401,14 +476,17 @@ All the basic assertions such as `assert_equal` defined in `Minitest::Assertions * [`ActionDispatch::SystemTestCase`](https://api.rubyonrails.org/classes/ActionDispatch/SystemTestCase.html) * [`Rails::Generators::TestCase`](https://api.rubyonrails.org/classes/Rails/Generators/TestCase.html) -Each of these classes include `Minitest::Assertions`, allowing us to use all of the basic assertions in our tests. +Each of these classes include `Minitest::Assertions`, allowing us to use all of +the basic assertions in our tests. -NOTE: For more information on `Minitest`, refer to its [documentation](http://docs.seattlerb.org/minitest). +NOTE: For more information on `Minitest`, refer to its +[documentation](http://docs.seattlerb.org/minitest). ### Transactions By default, Rails automatically wraps tests in a database transaction that is -rolled back after they finish. This makes tests independent of each other and means that changes to the database are only visible within a single test. +rolled back after they finish. This makes tests independent of each other and +means that changes to the database are only visible within a single test. ```ruby class MyTest < ActiveSupport::TestCase @@ -452,7 +530,8 @@ end 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. +Or we can run a single test file by passing the `bin/rails test` command the +filename containing the test cases. ```bash $ bin/rails test test/models/article_test.rb @@ -499,14 +578,16 @@ You can also run a range of tests by providing the line range. $ bin/rails test test/models/article_test.rb:6-20 # runs tests from line 6 to 20 ``` -You can also run an entire directory of tests by providing the path to the directory. +You can also run an entire directory of tests by providing the path to the +directory. ```bash $ bin/rails test test/controllers # run all tests from specific directory ``` -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: +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: ```bash $ bin/rails test -h @@ -554,42 +635,55 @@ Known extensions: rails, pride The Test Database ----------------- -Just about every Rails application interacts heavily with a database and, as a result, your tests will need a database to interact with as well. To write efficient tests, you'll need to understand how to set up this database and populate it with sample data. +Just about every Rails application interacts heavily with a database and, as a +result, your tests will need a database to interact with as well. To write +efficient tests, you'll need to understand how to set up this database and +populate it with sample data. -By default, every Rails application has three environments: development, test, and production. The database for each one of them is configured in `config/database.yml`. +By default, every Rails application has three environments: development, test, +and production. The database for each one of them is configured in +`config/database.yml`. -A dedicated test database allows you to set up and interact with test data in isolation. This way your tests can mangle test data with confidence, without worrying about the data in the development or production databases. +A dedicated test database allows you to set up and interact with test data in +isolation. This way your tests can interact with test data with confidence, +without worrying about the data in the development or production databases. ### Maintaining the Test Database Schema In order to run your tests, your test database will need to have the current structure. The test helper checks whether your test database has any pending -migrations. 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/rails db:migrate`) will -bring the schema up to date. +migrations. 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/rails db:migrate`) will bring +the schema up to date. -NOTE: If there were modifications to existing migrations, the test database needs to -be rebuilt. This can be done by executing `bin/rails test:db`. +NOTE: If there were modifications to existing migrations, the test database +needs to be rebuilt. This can be done by executing `bin/rails test:db`. ### Fixtures -For good tests, you'll need to give some thought to setting up test data. -In Rails, you can handle this by defining and customizing fixtures. -You can find comprehensive documentation in the [Fixtures API documentation](https://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html). +For good tests, you'll need to give some thought to setting up test data. In +Rails, you can handle this by defining and customizing fixtures. You can find +comprehensive documentation in the [Fixtures API +documentation](https://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html). #### What are Fixtures? -_Fixtures_ is a fancy word for sample data. Fixtures allow you to populate your testing database with predefined data before your tests run. Fixtures are database independent and written in YAML. There is one file per model. +_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. -NOTE: Fixtures are not designed to create every object that your tests need, and are best managed when only used for default data that can be applied to the common case. +NOTE: Fixtures are not designed to create every object that your tests need, and +are best managed when only used for default data that can be applied to the +common case. Fixtures can be stored in your `test/fixtures` directory. #### YAML -YAML-formatted fixtures are a human-friendly way to describe your sample data. These types of fixtures have the **.yml** file extension (as in `users.yml`). +YAML-formatted fixtures are a human-friendly way to describe your sample data. +These types of fixtures have the **.yml** file extension (as in `users.yml`). Here's a sample YAML fixture file: @@ -606,11 +700,13 @@ steve: profession: guy with keyboard ``` -Each fixture is given a name followed by an indented list of colon-separated key/value pairs. Records are typically separated by a blank line. You can place comments in a fixture file by using the # character in the first column. +Each fixture is given a name followed by an indented list of colon-separated +key/value pairs. Records are typically separated by a blank line. You can place +comments in a fixture file by using the # character in the first column. -If you are working with [associations](/association_basics.html), you can -define a reference node between two different fixtures. Here's an example with -a `belongs_to`/`has_many` association: +If you are working with [associations](/association_basics.html), you can define +a reference node between two different fixtures. Here's an example with a +`belongs_to`/`has_many` association: ```yaml # test/fixtures/categories.yml @@ -633,9 +729,18 @@ first_content: body:
Hello, from a fixture
``` -Notice the `category` key of the `first` Article found in `fixtures/articles.yml` has a value of `about`, and that the `record` key of the `first_content` entry found in `fixtures/action_text/rich_texts.yml` has a value of `first (Article)`. This hints to Active Record to load the Category `about` found in `fixtures/categories.yml` for the former, and Action Text to load the Article `first` found in `fixtures/articles.yml` for the latter. +Notice the `category` key of the `first` Article found in +`fixtures/articles.yml` has a value of `about`, and that the `record` key of the +`first_content` entry found in `fixtures/action_text/rich_texts.yml` has a value +of `first (Article)`. This hints to Active Record to load the Category `about` +found in `fixtures/categories.yml` for the former, and Action Text to load the +Article `first` found in `fixtures/articles.yml` for the latter. -NOTE: For associations to reference one another by name, you can use the fixture name instead of specifying the `id:` attribute on the associated fixtures. Rails will auto assign a primary key to be consistent between runs. For more information on this association behavior please read the [Fixtures API documentation](https://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html). +NOTE: For associations to reference one another by name, you can use the fixture +name instead of specifying the `id:` attribute on the associated fixtures. Rails +will auto assign a primary key to be consistent between runs. For more +information on this association behavior please read the [Fixtures API +documentation](https://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html). #### File Attachment Fixtures @@ -676,11 +781,15 @@ first_thumbnail_attachment: blob: first_thumbnail_blob ``` -[image/png]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types#image_types +[image/png]: + https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types#image_types #### ERB and Fixtures -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 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| %> @@ -699,11 +808,19 @@ default. Loading involves three steps: 2. Load the fixture data into the table 3. Dump the fixture data into a method in case you want to access it directly -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](https://www.postgresql.org/docs/current/sql-altertable.html)). +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 the permission to disable these triggers in the testing environment. +(In PostgreSQL, only superusers can disable all triggers. Read more about +PostgreSQL permissions +[here](https://www.postgresql.org/docs/current/sql-altertable.html)). #### Fixtures are Active Record Objects -Fixtures are instances of Active Record. As mentioned 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: +Fixtures are instances of Active Record. As mentioned above, you can access the +object directly because it is automatically available as a method whose scope is +local of the test case. For example: ```ruby # this will return the User object for the fixture named david @@ -712,12 +829,13 @@ users(:david) # this will return the property for david called id users(:david).id -# one can also access methods available on the User class +# methods available on the User class can also be accessed david = users(:david) david.call(david.partner) ``` -To get multiple fixtures at once, you can pass in a list of fixture names. For example: +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 @@ -728,22 +846,33 @@ users(:david, :steve) Model Testing ------------- -Model tests are used to test the various models of your application and their associated logic. +Model tests are used to test the various models of your application and their +associated logic. You can test this logic using the assertions and fixtures that +we've explored in the sections above. -Rails model tests are stored under the `test/models` directory. Rails provides -a generator to create a model test skeleton for you. +Rails model tests are stored under the `test/models` directory. Rails provides a +generator to create a model test skeleton for you. ```bash $ bin/rails generate test_unit:model article title:string body:text create test/models/article_test.rb ``` -Model tests don't have their own superclass like `ActionMailer::TestCase`. Instead, they inherit from [`ActiveSupport::TestCase`](https://api.rubyonrails.org/classes/ActiveSupport/TestCase.html). +Model tests don't have their own superclass like `ActionMailer::TestCase`. +Instead, they inherit from +[`ActiveSupport::TestCase`](https://api.rubyonrails.org/classes/ActiveSupport/TestCase.html). Functional Testing for Controllers ---------------------------------- -In Rails, a focus on 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 focusing on testing how your actions handle the requests and the expected result or response. Functional controller tests are sometimes used in cases where system tests are not appropriate, e.g., to confirm an API response. +In Rails, a focus on 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 focusing on testing how your actions +handle the requests and the expected result or response. Functional controller +tests are sometimes used in cases where system tests are not appropriate, e.g., +to confirm an API response. ### What to Include in Your Functional Tests @@ -754,7 +883,8 @@ You could test for things such as: * was the user successfully authenticated? * 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: +The easiest way to see functional tests in action is to generate a controller +using the scaffold generator: ```bash $ bin/rails generate scaffold_controller article title:string body:text @@ -766,11 +896,12 @@ 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. +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: +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: ```bash $ bin/rails generate test_unit:scaffold article @@ -780,11 +911,14 @@ create test/controllers/articles_controller_test.rb ... ``` -NOTE: if you are generating test scaffold code, you will see an `@article` value is set and used throughout the test file. -This instance of `article` uses the attributes nested within a `:one` key in the `test/fixtures/articles.yml` file. Make sure you have set the key and related values before you try to +NOTE: if you are generating test scaffold code, you will see an `@article` value +is set and used throughout the test file. This instance of `article` uses the +attributes nested within a `:one` key in the `test/fixtures/articles.yml` file. +Make sure you have set the key and related values in this file before you try to run the tests. -Let's take a look at one such test, `test_should_get_index` from the file `articles_controller_test.rb`. +Let's take a look at one such test, `test_should_get_index` from the file +`articles_controller_test.rb`. ```ruby # articles_controller_test.rb @@ -796,44 +930,52 @@ class ArticlesControllerTest < ActionDispatch::IntegrationTest end ``` -In the `test_should_get_index` test, Rails simulates a request on the action called `index`, making sure the request was successful -and also ensuring that the right response body has been generated. +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 `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`). +* 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. +* `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: +Example: Calling the `:show` action for the first `Article`, passing in an +`HTTP_REFERER` header: ```ruby 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: +Another example: Calling the `:update` action for the last `Article`, passing in +new text for the `title` in `params`, as an Ajax request: ```ruby 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: +One more example: Calling the `:create` action to create a new article, passing +in text for the `title` in `params`, as JSON request: ```ruby post articles_path, params: { article: { title: "Ahoy!" } }, as: :json ``` -NOTE: If you try running the `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. +NOTE: If you try running the `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 the `test_should_create_article` test in `articles_controller_test.rb` so that this test passes: +Let us modify the `test_should_create_article` test in +`articles_controller_test.rb` so that this test passes: ```ruby test "should create article" do @@ -847,7 +989,9 @@ end You can now run this test and it will pass. -NOTE: If you followed the steps in the [Basic Authentication](getting_started.html#basic-authentication) section, you'll need to add authorization to every request header to get all the tests passing: +NOTE: If you followed the steps in the [Basic +Authentication](getting_started.html#basic-authentication) section, you'll need +to add authorization to every request header to get all the tests passing: ```ruby post articles_url, params: { article: { body: "Rails is awesome!", title: "Hello Rails" } }, headers: { Authorization: ActionController::HttpAuthentication::Basic.encode_credentials("dhh", "secret") } @@ -855,7 +999,8 @@ post articles_url, params: { article: { body: "Rails is awesome!", title: "Hello ### Available Request Types for Functional Tests -If you're familiar with the HTTP protocol, you'll know that `get` is a type of request. There are 6 request types supported in Rails functional tests: +If you're familiar with the HTTP protocol, you'll know that `get` is a type of +request. There are 6 request types supported in Rails functional tests: * `get` * `post` @@ -864,14 +1009,20 @@ If you're familiar with the HTTP protocol, you'll know that `get` is a type of r * `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. +All of the 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` most +often. -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. +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. ### Testing XHR (Ajax) Requests -An AJAX request (Asynchronous Javscript and XML) is a type of request where information is sent over a server without the page reloading. To test Ajax requests, you can specify the `xhr: true` -option to `get`, `post`, `patch`, `put`, and `delete` methods. For example: +An AJAX request (Asynchronous Javscript and XML) is a type of request where +information is sent over a server without the page reloading. To test Ajax +requests, you can specify the `xhr: true` option to `get`, `post`, `patch`, +`put`, and `delete` methods. For example: ```ruby test "ajax request" do @@ -885,13 +1036,16 @@ end ### Testing Other Request Objects -After a request has been made and processed, you will have 3 Hash objects ready for use: +After any 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: +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: ```ruby flash["gordon"] # or flash[:gordon] @@ -901,7 +1055,8 @@ cookies["are_good_for_u"] # or cookies[:are_good_for_u] ### Instance Variables -You also have access to three instance variables in your functional tests after a request is made: +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 @@ -922,8 +1077,9 @@ end ### Setting Headers and CGI Variables -HTTP headers are pieces of information sent along with HTTP requests to provide important metadata. -CGI variables are environment variables used to exchange information between the web server and the application. +HTTP headers are pieces of information sent along with HTTP requests to provide +important metadata. CGI variables are environment variables used to exchange +information between the web server and the application. HTTP headers and CGI variables can be tested by being passed as headers: @@ -937,7 +1093,8 @@ get articles_url, headers: { "HTTP_REFERER": "http://example.com/home" } # simul ### Testing `flash` Notices -If you remember from earlier, one of the three hash objects we have access to was `flash`. +As we have seen in the secctions above, one of the three hash objects we have +access to is `flash`. We want to add a `flash` message to our blog application whenever someone successfully creates a new Article. @@ -979,7 +1136,8 @@ ArticlesControllerTest#test_should_create_article [/test/controllers/articles_co 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: +Let's implement the flash message now in our controller. Our `:create` action +should now look like this: ```ruby def create @@ -1010,14 +1168,15 @@ Finished in 0.081972s, 12.1993 runs/s, 48.7972 assertions/s. 1 runs, 4 assertions, 0 failures, 0 errors, 0 skips ``` -NOTE: If you generated your controller using the scaffold generator, the flash message will already be -implemented in your `create` action. +NOTE: If you generated your controller using the scaffold generator, the flash +message will already be implemented in your `create` action. ### Putting It Together -At this point we have looked at tests for the `:index` as well as the`:create` action. What about dealing with existing data? +At this point we have looked at tests for the `:index` as well as the`:create` +action. What about the other actions? -Let's make sure we have a test for the `:show` action: +Let's make sure we have a test for `:show`: ```ruby test "should show article" do @@ -1027,9 +1186,10 @@ test "should show article" do end ``` -If you remember from our discussion earlier on fixtures, the `articles()` method will give us access to our Articles fixtures. +If you remember from our discussion earlier on fixtures, the `articles()` method +will give us access to our articles fixtures. -How about deleting an existing Article? +How about deleting an existing article? ```ruby test "should destroy article" do @@ -1042,7 +1202,7 @@ test "should destroy article" do end ``` -We can also consider a test for updating an existing Article. +We can also consider a test for updating an existing article. ```ruby test "should update article" do @@ -1057,7 +1217,10 @@ test "should update article" do end ``` -Notice we're starting to see some duplication in these three tests, they both access the same Article fixture data. It is possible to D.R.Y. this up ('Don't Repeat Yourself') by using the `setup` and `teardown` methods provided by `ActiveSupport::Callbacks`. +Notice we're starting to see some duplication in these three tests, they both +access the same article fixture data. It is possible to D.R.Y. this up ('Don't +Repeat Yourself') by using the `setup` and `teardown` methods provided by +`ActiveSupport::Callbacks`. Our tests now might look something like the below. @@ -1101,12 +1264,16 @@ class ArticlesControllerTest < ActionDispatch::IntegrationTest end ``` -NOTE: 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. +NOTE: 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. Integration Testing ------------------- -Integration tests take functional controller tests one step further, as they are focussed on testing how various parts of our application interact. They are generally used to test important workflows within our application. Rails integration tests can be created in the `test/integration` directory. +Integration tests take functional controller tests one step further, as they are +focussed on testing how various parts of our application interact. They are +generally used to test important workflows within our application. Rails +integration tests can be stored in the `test/integration` directory. Rails provides a generator to create an integration test skeleton for us. @@ -1128,11 +1295,16 @@ class UserFlowsTest < ActionDispatch::IntegrationTest end ``` -Here the test is inheriting from `ActionDispatch::IntegrationTest`. This makes some additional [helpers](testing.html#helpers-available-for-integration-tests) available for us to use in our integration tests, alongside the standard testing helpers. +Here the test is inheriting from `ActionDispatch::IntegrationTest`. This makes +some additional [helpers](testing.html#helpers-available-for-integration-tests) +available for us to use in our integration tests, alongside the standard testing +helpers. ### 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. +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: @@ -1156,18 +1328,23 @@ require "test_helper" class BlogFlowTest < ActionDispatch::IntegrationTest test "can see the welcome page" do get "/" - assert_select "h1", "Welcome#index" + assert_dom "h1", "Welcome#index" end end ``` -We will take a look at `assert_select` to query the resulting HTML of a request in the [Testing Views](#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. +We will take a look at `assert_dom` to query the resulting HTML of a request in +the [Testing Views](#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. +When we visit our root path, we should see `welcome/index.html.erb` rendered for +the view. So this assertion should pass. #### Creating Articles Integration -We can also test our ability to create a new article in our blog and display the resulting article. +We can also test our ability to create a new article in our blog and display the +resulting article. ```ruby test "can create an article" do @@ -1179,15 +1356,17 @@ test "can create an article" do assert_response :redirect follow_redirect! assert_response :success - assert_select "p", "Title:\n can create" + assert_dom "p", "Title:\n can create" end ``` 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. +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: +After this we make a post request to the `:create` action of our Articles +controller: ```ruby post "/articles", @@ -1196,36 +1375,55 @@ assert_response :redirect follow_redirect! ``` -The two lines following the request are to handle the redirect we setup when creating a new article. +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. +NOTE: 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. +Finally we can assert that our response was successful and our new article is +readable on the page. #### 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. +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 adding comments, editing comments or removing articles. Integration tests +are a great place to experiment with all kinds of use cases for our +applications. ### Helpers Available for Integration Tests -Here are some of the helpers we can choose from in our integration tests. +Here are some of the other helpers we can choose from in our integration tests. -For dealing with the integration test runner, see [`ActionDispatch::Integration::Runner`](https://api.rubyonrails.org/classes/ActionDispatch/Integration/Runner.html). +For dealing with the integration test runner, see +[`ActionDispatch::Integration::Runner`](https://api.rubyonrails.org/classes/ActionDispatch/Integration/Runner.html). -When performing requests, we will have [`ActionDispatch::Integration::RequestHelpers`](https://api.rubyonrails.org/classes/ActionDispatch/Integration/RequestHelpers.html) available for our use. +When performing requests, we will have +[`ActionDispatch::Integration::RequestHelpers`](https://api.rubyonrails.org/classes/ActionDispatch/Integration/RequestHelpers.html) +available for our use. -If we need to upload files, take a look at [`ActionDispatch::TestProcess::FixtureFile`](https://api.rubyonrails.org/classes/ActionDispatch/TestProcess/FixtureFile.html) to help. +If we need to upload files, take a look at +[`ActionDispatch::TestProcess::FixtureFile`](https://api.rubyonrails.org/classes/ActionDispatch/TestProcess/FixtureFile.html) +to help. -If we need to modify the session, or state of our integration test, take a look at [`ActionDispatch::Integration::Session`](https://api.rubyonrails.org/classes/ActionDispatch/Integration/Session.html) to help. +If we need to modify the session, or state of our integration test, take a look +at +[`ActionDispatch::Integration::Session`](https://api.rubyonrails.org/classes/ActionDispatch/Integration/Session.html) +to help. System Testing -------------- -Similarly to integration testing, system testing also allows you to test how the components of your app work together, but from the point of view of a user. It does this by running tests -in either a real or a headless browser (a browser which runs in the background without opening a visible window). System tests use Capybara under the hood. +Similarly to integration testing, system testing also allows you to test how the +components of your app work together, but from the point of view of a user. It +does this by running tests in either a real or a headless browser (a browser +which runs in the background without opening a visible window). System tests use +Capybara under the hood. For creating Rails system tests, you use the `test/system` directory in your -application. Rails provides a generator to create a system test skeleton for you. +application. Rails provides a generator to create a system test skeleton for +you. ```bash $ bin/rails generate system_test users @@ -1248,21 +1446,21 @@ end ``` By default, system tests are run with the Selenium driver, using the Chrome -browser, and a screen size of 1400x1400. The next section explains how to -change the default settings. +browser, and a screen size of 1400x1400. The next section explains how to change +the default settings. ### Changing the Default Settings -Rails makes changing the default settings for system tests very simple. All -the setup is abstracted away so you can focus on writing your tests. +Rails makes changing the default settings for system tests very simple. All the +setup is abstracted away so you can focus on writing your tests. -When you generate a new application or scaffold, an `application_system_test_case.rb` file -is created in the test directory. This is where all the configuration for your -system tests should live. +When you generate a new application or scaffold, an +`application_system_test_case.rb` file is created in the test directory. This is +where all the configuration for your system tests should live. -If you want to change the default settings you can change what the system -tests are "driven by". Say you want to change the driver from Selenium to -Cuprite. First add the `cuprite` gem to your `Gemfile`. Then in your +If you want to change the default settings, you can change what the system tests +are "driven by". Say you want to change the driver from Selenium to Cuprite. +First add the `cuprite` gem to your `Gemfile`. Then in your `application_system_test_case.rb` file do the following: ```ruby @@ -1288,8 +1486,9 @@ class ApplicationSystemTestCase < ActionDispatch::SystemTestCase end ``` -If you want to use a headless browser, you could use Headless Chrome or Headless Firefox by adding -`headless_chrome` or `headless_firefox` in the `:using` argument. +If you want to use a headless browser, you could use Headless Chrome or Headless +Firefox by adding `headless_chrome` or `headless_firefox` in the `:using` +argument. ```ruby require "test_helper" @@ -1299,9 +1498,9 @@ class ApplicationSystemTestCase < ActionDispatch::SystemTestCase end ``` -If you want to use a remote browser, e.g. -[Headless Chrome in Docker](https://github.com/SeleniumHQ/docker-selenium), -you have to add a remote `url` and set `browser` as remote through `options`. +If you want to use a remote browser, e.g. [Headless Chrome in +Docker](https://github.com/SeleniumHQ/docker-selenium), you have to add a remote +`url` and set `browser` as remote through `options`. ```ruby require "test_helper" @@ -1323,9 +1522,9 @@ Now you should get a connection to the remote browser. $ SELENIUM_REMOTE_URL=http://localhost:4444/wd/hub bin/rails test:system ``` -If your application in test is running remote too, e.g. within a Docker container, -Capybara needs more input about how to -[call remote servers](https://github.com/teamcapybara/capybara#calling-remote-servers). +If your application in test is running remote too, e.g. within a Docker +container, Capybara needs more input about how to [call remote +servers](https://github.com/teamcapybara/capybara#calling-remote-servers). ```ruby require "test_helper" @@ -1344,16 +1543,18 @@ Now you should get a connection to a remote browser and server, regardless if it is running in a Docker container or CI. If your Capybara configuration requires more setup than provided by Rails, this -additional configuration could be added into the `application_system_test_case.rb` -file. +additional configuration could be added into the +`application_system_test_case.rb` file. -Please see [Capybara's documentation](https://github.com/teamcapybara/capybara#setup) -for additional settings. +Please see [Capybara's +documentation](https://github.com/teamcapybara/capybara#setup) for additional +settings. ### Implementing a System Test Now we're going to add a system test to our blog application. We'll demonstrate -writing a system test by visiting the index page and creating a new blog article. +writing a system test by visiting the index page and creating a new blog +article. If you used the scaffold generator, a system test skeleton was automatically created for you. If you didn't use the scaffold generator, start by creating a @@ -1392,9 +1593,9 @@ Run the system tests. $ bin/rails test:system ``` -NOTE: By default, running `bin/rails test` won't run your system tests. -Make sure to run `bin/rails test:system` to actually run them. -You can also run `bin/rails test:all` to run all tests, including system tests. +NOTE: By default, running `bin/rails test` won't run your system tests. Make +sure to run `bin/rails test:system` to actually run them. You can also run +`bin/rails test:all` to run all tests, including system tests. #### Creating Articles System Test @@ -1425,15 +1626,16 @@ Then the test will fill in the title and body of the article with the specified text. Once the fields are filled in, "Create Article" is clicked on which will send a POST request to create the new article in the database. -We will be redirected back to the articles index page and there we assert -that the text from the new article's title is on the articles index page. +We will be redirected back to the articles index page and there we assert that +the text from the new article's title is on the articles index page. #### Testing for Multiple Screen Sizes -If you want to test for mobile sizes on top of testing for desktop, -you can create another class that inherits from `ActionDispatch::SystemTestCase` and use it in your -test suite. In this example a file called `mobile_system_test_case.rb` is created -in the `/test` directory with the following configuration. +If you want to test for mobile sizes on top of testing for desktop, you can +create another class that inherits from `ActionDispatch::SystemTestCase` and use +it in your test suite. In this example a file called +`mobile_system_test_case.rb` is created in the `/test` directory with the +following configuration. ```ruby require "test_helper" @@ -1443,8 +1645,9 @@ class MobileSystemTestCase < ActionDispatch::SystemTestCase end ``` -To use this configuration, create a test inside `test/system` that inherits from `MobileSystemTestCase`. -Now you can test your app using multiple different configurations. +To use this configuration, create a test inside `test/system` that inherits from +`MobileSystemTestCase`. Now you can test your app using multiple different +configurations. ```ruby require "mobile_system_test_case" @@ -1456,11 +1659,14 @@ class PostsTest < MobileSystemTestCase end end ``` + #### Screenshot Helper -The [`ScreenshotHelper`](https://api.rubyonrails.org/v5.1.7/classes/ActionDispatch/SystemTesting/TestHelpers/ScreenshotHelper.html) is a helper designed to capture screenshots of your tests. -This can be helpful for viewing the browser at the point a test failed, or -to view screenshots later for debugging. +The +[`ScreenshotHelper`](https://api.rubyonrails.org/v5.1.7/classes/ActionDispatch/SystemTesting/TestHelpers/ScreenshotHelper.html) +is a helper designed to capture screenshots of your tests. This can be helpful +for viewing the browser at the point a test failed, or to view screenshots later +for debugging. Two methods are provided: `take_screenshot` and `take_failed_screenshot`. `take_failed_screenshot` is automatically included in `before_teardown` inside @@ -1471,17 +1677,18 @@ take a screenshot of the browser. #### Taking It Further -The beauty of system testing is that it is similar to [integration testing](testing.html#integration-testing) in that it tests the user's interaction with your controller, model, and view, but -system testing is much more robust and actually tests your application as if -a real user were using it. With system tests, you can test anything that the user -themselves would do in your application such as commenting, deleting articles, -publishing draft articles, etc. +The beauty of system testing is that it is similar to [integration +testing](#integration-testing) in that it tests the user's interaction with your +controller, model, and view, but system testing is much more robust and actually +tests your application as if a real user were using it. With system tests, you +can test anything that the user themselves would do in your application such as +commenting, deleting articles, publishing draft articles, etc. Test Helpers ------------ -To avoid code duplication, you can add your own test helpers. -Sign in helper can be a good example: +To avoid code duplication, you can add your own test helpers. Sign in helper can +be a good example: ```ruby # test/test_helper.rb @@ -1513,8 +1720,9 @@ end #### 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`. +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`. ```ruby # test/test_helpers/multiple_assertions.rb @@ -1553,32 +1761,45 @@ end #### 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 +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 ```ruby # 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. +This has the downside of increasing the boot-up time, as opposed to manually +requiring only the necessary files in your individual tests. Testing Routes -------------- -Like everything else in your Rails application, you can test your routes. Route tests reside in `test/controllers/` or are part of controller tests. +Like everything else in your Rails application, you can test your routes. Route +tests reside in `test/controllers/` or are part of controller tests. -NOTE: If your application has complex routes, Rails provides a number of useful helpers to test them. +NOTE: If your application has complex routes, Rails provides a number of useful +helpers to test them. -For more information on routing assertions available in Rails, see the API documentation for [`ActionDispatch::Assertions::RoutingAssertions`](https://api.rubyonrails.org/classes/ActionDispatch/Assertions/RoutingAssertions.html). +For more information on routing assertions available in Rails, see the API +documentation for +[`ActionDispatch::Assertions::RoutingAssertions`](https://api.rubyonrails.org/classes/ActionDispatch/Assertions/RoutingAssertions.html). Testing Views ------------- -Testing the response to your request by asserting the presence of key HTML elements and their content is one way to test the views of your application. Like route tests, view tests reside in `test/controllers/` or are part of controller tests. +Testing the response to your request by asserting the presence of key HTML +elements and their content is one way to test the views of your application. +Like route tests, view tests reside in `test/controllers/` or are part of +controller tests. -Methods like `assert_dom` and `assert_dom_equal` allow you to query HTML elements of the response by using a simple yet powerful syntax. +Methods like `assert_dom` and `assert_dom_equal` allow you to query HTML +elements of the response by using a simple yet powerful syntax. -`assert_dom` is an assertion that will return true if matching elements are found. For example, you could verify that the page title is "Welcome to the Rails Testing Guide" as follows: +`assert_dom` is an assertion that will return true if matching elements are +found. For example, you could verify that the page title is "Welcome to the +Rails Testing Guide" as follows: ```ruby assert_dom "title", "Welcome to the Rails Testing Guide" @@ -1586,8 +1807,8 @@ assert_dom "title", "Welcome to the Rails Testing Guide" You can also use nested `assert_dom` blocks for deeper investigation. -In the following example, the inner `assert_dom` for `li.menu_item` runs -within the collection of elements selected by the outer block: +In the following example, the inner `assert_dom` for `li.menu_item` runs within +the collection of elements selected by the outer block: ```ruby assert_dom "ul.navigation" do @@ -1595,7 +1816,10 @@ assert_dom "ul.navigation" do end ``` -A collection of selected elements may also be iterated through so that `assert_dom` 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. +A collection of selected elements may also be iterated through so that +`assert_dom` 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. ```ruby assert_dom "ol" do |elements| @@ -1609,14 +1833,16 @@ assert_dom "ol" do end ``` -The `assert_dom_equal` method tests two HTML strings for equivalency, as in the example below: +The `assert_dom_equal` method tests two HTML strings for equivalency, as in the +example below: ```ruby assert_dom_equal 'Read more', link_to("Read more", "http://www.further-reading.com") ``` -These assertions are quite powerful. For more advanced usage, refer to their [documentation](https://github.com/rails/rails-dom-testing). +These assertions are quite powerful. For more advanced usage, refer to their +[documentation](https://github.com/rails/rails-dom-testing). In order to integrate with [rails-dom-testing][], tests that inherit from `ActionView::TestCase` declare a `document_root_element` method that returns the @@ -1635,9 +1861,12 @@ test "renders a link to itself" do end ``` -If your application uses Ruby >= 3.0 or higher, depends on [Nokogiri >= 1.14.0](https://github.com/sparklemotion/nokogiri/releases/tag/v1.14.0) or -higher, and depends on [Minitest >= >5.18.0](https://github.com/minitest/minitest/blob/v5.18.0/History.rdoc#5180--2023-03-04-), -`document_root_element` supports [Ruby's Pattern Matching](https://docs.ruby-lang.org/en/master/syntax/pattern_matching_rdoc.html): +If your application uses Ruby >= 3.0 or higher, depends on [Nokogiri >= +1.14.0](https://github.com/sparklemotion/nokogiri/releases/tag/v1.14.0) or +higher, and depends on [Minitest >= +>5.18.0](https://github.com/minitest/minitest/blob/v5.18.0/History.rdoc#5180--2023-03-04-), +`document_root_element` supports [Ruby's Pattern +Matching](https://docs.ruby-lang.org/en/master/syntax/pattern_matching_rdoc.html): ```ruby test "renders a link to itself" do @@ -1653,7 +1882,8 @@ test "renders a link to itself" do end ``` -If you'd like to access the same [Capybara-powered Assertions](https://rubydoc.info/github/teamcapybara/capybara/master/Capybara/Minitest/Assertions) +If you'd like to access the same [Capybara-powered +Assertions](https://rubydoc.info/github/teamcapybara/capybara/master/Capybara/Minitest/Assertions) that your [Functional and System Testing](#functional-and-system-testing) tests utilize, you can define a base class that inherits from `ActionView::TestCase` and transforms the `document_root_element` into a `page` method: @@ -1691,10 +1921,10 @@ Starting in Action View version 7.1, the `#rendered` helper method returns an object capable of parsing the view partial's rendered content. To transform the `String` content returned by the `#rendered` method into an -object, define a parser by calling `.register_parser`. Calling -`.register_parser :rss` defines a `#rendered.rss` helper method. For example, -to parse rendered [RSS content][] into an object with `#rendered.rss`, register -a call to `RSS::Parser.parse`: +object, define a parser by calling `.register_parser`. Calling `.register_parser +:rss` defines a `#rendered.rss` helper method. For example, to parse rendered +[RSS content][] into an object with `#rendered.rss`, register a call to +`RSS::Parser.parse`: ```ruby register_parser :rss, -> rendered { RSS::Parser.parse(rendered) } @@ -1710,8 +1940,10 @@ end By default, `ActionView::TestCase` defines a parser for: -* `:html` - returns an instance of [Nokogiri::XML::Node](https://nokogiri.org/rdoc/Nokogiri/XML/Node.html) -* `:json` - returns an instance of [ActiveSupport::HashWithIndifferentAccess](https://api.rubyonrails.org/classes/ActiveSupport/HashWithIndifferentAccess.html) +* `:html` - returns an instance of + [Nokogiri::XML::Node](https://nokogiri.org/rdoc/Nokogiri/XML/Node.html) +* `:json` - returns an instance of + [ActiveSupport::HashWithIndifferentAccess](https://api.rubyonrails.org/classes/ActiveSupport/HashWithIndifferentAccess.html) ```ruby test "renders HTML" do @@ -1754,9 +1986,14 @@ end ### Testing View Partials -[Partial](layouts_and_rendering.html#using-partials) templates - usually called "partials" - are another device for breaking the rendering process into more manageable chunks. With partials, you can extract pieces of code from your templates to separate files and reuse them throughout your templates. +[Partial](layouts_and_rendering.html#using-partials) templates - usually called +"partials" - are another device for breaking the rendering process into more +manageable chunks. With partials, you can extract pieces of code from your +templates to separate files and reuse them throughout your templates. -View tests provide an opportunity to test that partials render content the way you expect. View partial tests can be stored in `test/views/` and inherit from `ActionView::TestCase`. +View tests provide an opportunity to test that partials render content the way +you expect. View partial tests can be stored in `test/views/` and inherit from +`ActionView::TestCase`. To render a partial, call `render` like you would in a template. The content is available through the test-local `rendered` method: @@ -1773,7 +2010,10 @@ class ArticlePartialTest < ActionView::TestCase end ``` -Tests that inherit from `ActionView::TestCase` also have access to [`assert_dom`](#testing-views) and the [other additional view-based assertions](#additional-view-based-assertions) provided by [rails-dom-testing][]: +Tests that inherit from `ActionView::TestCase` also have access to +[`assert_dom`](#testing-views) and the [other additional view-based +assertions](#additional-view-based-assertions) provided by +[rails-dom-testing][]: ```ruby test "renders a link to itself" do @@ -1820,9 +2060,10 @@ Moreover, since the test class extends from `ActionView::TestCase`, you have access to Rails' helper methods such as `link_to` or `pluralize`. Testing Mailers --------------------- +--------------- -Your mailer classes - like every other part of your Rails application - should be tested to ensure that they are working as expected. +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: @@ -1832,21 +2073,39 @@ The goals of testing your mailer classes are to ensure that: #### 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](testing.html#fixtures)). In the functional tests you don't so much test the 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. +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](#fixtures)). In the functional tests you don't so much test the +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. +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. #### Mailer Fixtures -For the purposes of unit testing a mailer, fixtures are used to provide an example of how the output _should_ look. Because these are example emails, and not Active Record data like the other fixtures, they are kept in their own subdirectory apart from the other fixtures. The name of the directory within `test/fixtures` directly corresponds to the name of the mailer. So, for a mailer named `UserMailer`, the fixtures should reside in `test/fixtures/user_mailer` directory. +For the purposes of unit testing a mailer, fixtures are used to provide an +example of how the output _should_ look. Because these are example emails, and +not Active Record data like the other fixtures, they are kept in their own +subdirectory apart from the other fixtures. The name of the directory within +`test/fixtures` directly corresponds to the name of the mailer. So, for a mailer +named `UserMailer`, the fixtures should reside in `test/fixtures/user_mailer` +directory. -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. +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. #### The Basic Test Case -Here's a unit test to test a mailer named `UserMailer` whose action `invite` is used to send an invitation to a friend. It is an adapted version of the base test created by the generator for an `invite` action. +Here's a unit test to test a mailer named `UserMailer` whose action `invite` is +used to send an invitation to a friend. It is an adapted version of the base +test created by the generator for an `invite` action. ```ruby require "test_helper" @@ -1871,9 +2130,14 @@ class UserMailerTest < ActionMailer::TestCase end ``` -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. +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. -NOTE: `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`. +NOTE: `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: @@ -1887,17 +2151,30 @@ Cheers! #### Configuring the Delivery Method for Test -The line `ActionMailer::Base.delivery_method = :test` in `config/environments/test.rb` sets the delivery method to test mode so that the email will not actually be delivered (useful to avoid spamming your users while testing). Instead, the email will be appended to an array (`ActionMailer::Base.deliveries`). +The line `ActionMailer::Base.delivery_method = :test` in +`config/environments/test.rb` sets the delivery method to test mode so that the +email will not actually be delivered (useful to avoid spamming your users while +testing). Instead, the email will be appended to an array +(`ActionMailer::Base.deliveries`). -NOTE: 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` +NOTE: 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` #### Testing Enqueued Emails -You can use the `assert_enqueued_email_with` assertion to confirm that the email has been enqueued with all of the expected mailer method arguments and/or parameterized mailer parameters. This allows you to match any emails that have been enqueued with the `deliver_later` method. +You can use the `assert_enqueued_email_with` assertion to confirm that the email +has been enqueued with all of the expected mailer method arguments and/or +parameterized mailer parameters. This allows you to match any emails that have +been enqueued with the `deliver_later` method. -As with the basic test case, we create the email and store the returned object in the `email` variable. The following examples include variations of passing arguments and/or parameters. +As with the basic test case, we create the email and store the returned object +in the `email` variable. The following examples include variations of passing +arguments and/or parameters. -This example will assert that the email has been enqueued with the correct arguments: +This example will assert that the email has been enqueued with the correct +arguments: ```ruby require "test_helper" @@ -1915,7 +2192,8 @@ class UserMailerTest < ActionMailer::TestCase end ``` -This example will assert that a mailer has been enqueued with the correct mailer method named arguments by passing a hash of the arguments as `args`: +This example will assert that a mailer has been enqueued with the correct mailer +method named arguments by passing a hash of the arguments as `args`: ```ruby require "test_helper" @@ -1934,7 +2212,9 @@ class UserMailerTest < ActionMailer::TestCase end ``` -This example will assert that a parameterized mailer has been enqueued with the correct parameters and arguments. The mailer parameters are passed as `params` and the mailer method arguments as `args`: +This example will assert that a parameterized mailer has been enqueued with the +correct parameters and arguments. The mailer parameters are passed as `params` +and the mailer method arguments as `args`: ```ruby require "test_helper" @@ -1953,7 +2233,8 @@ class UserMailerTest < ActionMailer::TestCase end ``` -This example shows an alternative way to test that a parameterized mailer has been enqueued with the correct parameters: +This example shows an alternative way to test that a parameterized mailer has +been enqueued with the correct parameters: ```ruby require "test_helper" @@ -1973,7 +2254,10 @@ end ### 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: +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: ```ruby # Integration Test @@ -2006,7 +2290,13 @@ class UsersTest < ActionDispatch::SystemTestCase end ``` -NOTE: 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_email_with` ([examples above](#testing-enqueued-emails)) or `assert_enqueued_emails` methods. More information can be found in the [documentation here](https://api.rubyonrails.org/classes/ActionMailer/TestHelper.html). +NOTE: 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_email_with` ([examples +above](#testing-enqueued-emails)) or `assert_enqueued_emails` methods. More +information can be found in the +[documentation](https://api.rubyonrails.org/classes/ActionMailer/TestHelper.html). Testing Jobs ------------ @@ -2042,9 +2332,12 @@ The test uses `perform_enqueued_jobs` and [`perform_later`][] instead of [`perform_now`][] so that if retries are configured, retry failures are caught by the test instead of being re-enqueued and ignored. -[`perform_enqueued_jobs`]: https://api.rubyonrails.org/classes/ActiveJob/TestHelper.html#method-i-perform_enqueued_jobs -[`perform_later`]: https://api.rubyonrails.org/classes/ActiveJob/Enqueuing/ClassMethods.html#method-i-perform_later -[`perform_now`]: https://api.rubyonrails.org/classes/ActiveJob/Execution/ClassMethods.html#method-i-perform_now +[`perform_enqueued_jobs`]: + https://api.rubyonrails.org/classes/ActiveJob/TestHelper.html#method-i-perform_enqueued_jobs +[`perform_later`]: + https://api.rubyonrails.org/classes/ActiveJob/Enqueuing/ClassMethods.html#method-i-perform_later +[`perform_now`]: + https://api.rubyonrails.org/classes/ActiveJob/Execution/ClassMethods.html#method-i-perform_now ### Testing Jobs in Context @@ -2074,12 +2367,17 @@ class AccountTest < ActiveSupport::TestCase end ``` -[`ActiveJob::TestHelper`]: https://api.rubyonrails.org/classes/ActiveJob/TestHelper.html -[`assert_enqueued_with`]: https://api.rubyonrails.org/classes/ActiveJob/TestHelper.html#method-i-assert_enqueued_with +[`ActiveJob::TestHelper`]: + https://api.rubyonrails.org/classes/ActiveJob/TestHelper.html +[`assert_enqueued_with`]: + https://api.rubyonrails.org/classes/ActiveJob/TestHelper.html#method-i-assert_enqueued_with ### Testing that Exceptions are Raised -Testing that your job raises an exception in certain cases can be tricky, especially when you have retries configured. The `perform_enqueued_jobs` helper fails any test where a job raises an exception, so to have the test succeed when the exception is raised you have to call the job's `perform` method directly. +Testing that your job raises an exception in certain cases can be tricky, +especially when you have retries configured. The `perform_enqueued_jobs` helper +fails any test where a job raises an exception, so to have the test succeed when +the exception is raised you have to call the job's `perform` method directly. ```ruby require "test_helper" @@ -2094,21 +2392,25 @@ class BillingJobTest < ActiveJob::TestCase end ``` -This method is not recommended in general, as it circumvents some parts of the framework, such as argument serialization. +This method is not recommended in general, as it circumvents some parts of the +framework, such as argument serialization. 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 +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. ### Connection Test Case -By default, when you generate a 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. +By default, when you generate a 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: +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: ```ruby class ApplicationCable::ConnectionTest < ActionCable::Connection::TestCase @@ -2140,12 +2442,15 @@ test "connects with cookies" do end ``` -See the API documentation for [`ActionCable::Connection::TestCase`](https://api.rubyonrails.org/classes/ActionCable/Connection/TestCase.html) for more information. +See the API documentation for +[`ActionCable::Connection::TestCase`](https://api.rubyonrails.org/classes/ActionCable/Connection/TestCase.html) +for more information. ### 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: +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: ```ruby require "test_helper" @@ -2162,9 +2467,11 @@ class ChatChannelTest < ActionCable::Channel::TestCase end ``` -This test is pretty simple and only asserts that the channel subscribes the connection to a particular stream. +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: +You can also specify the underlying connection identifiers. Here's an example +test with a web notifications channel: ```ruby require "test_helper" @@ -2180,13 +2487,19 @@ class WebNotificationsChannelTest < ActionCable::Channel::TestCase end ``` -See the API documentation for [`ActionCable::Channel::TestCase`](https://api.rubyonrails.org/classes/ActionCable/Channel/TestCase.html) for more information. +See the API documentation for +[`ActionCable::Channel::TestCase`](https://api.rubyonrails.org/classes/ActionCable/Channel/TestCase.html) +for more information. ### 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`](https://api.rubyonrails.org/classes/ActionCable/TestHelper.html). +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`](https://api.rubyonrails.org/classes/ActionCable/TestHelper.html). -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 +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: @@ -2202,8 +2515,8 @@ class ProductTest < ActionCable::TestCase end ``` -If you want to test the broadcasting made with `Channel.broadcast_to`, you should use -`Channel.broadcasting_for` to generate an underlying stream name: +If you want to test the broadcasting made with `Channel.broadcast_to`, you +should use `Channel.broadcasting_for` to generate an underlying stream name: ```ruby # app/jobs/chat_relay_job.rb @@ -2234,7 +2547,9 @@ end Running tests in Continuous Integration (CI) -------------------------------------------- -Continuous Integration (CI) is a development practice where changes are frequently integrated into the main codebase, and as such, are automatically tested before merge. +Continuous Integration (CI) is a development practice where changes are +frequently integrated into the main codebase, and as such, are automatically +tested before merge. To run all tests in a CI environment, there's just one command you need: @@ -2242,22 +2557,24 @@ To run all tests in a CI environment, there's just one command you need: $ bin/rails test ``` -If you are using [System Tests](#system-testing), `bin/rails test` will not run them, since -they can be slow. To also run them, add another CI step that runs `bin/rails test:system`, -or change your first step to `bin/rails test:all`, which runs all tests including system tests. +If you are using [System Tests](#system-testing), `bin/rails test` will not run +them, since they can be slow. To also run them, add another CI step that runs +`bin/rails test:system`, or change your first step to `bin/rails test:all`, +which runs all tests including system tests. Parallel Testing ---------------- -Parallel testing allows you to parallelize your test suite. While forking processes is the -default method, threading is supported as well. Running tests in parallel reduces the time it -takes your entire test suite to run. +Parallel testing allows you to parallelize your test suite. While forking +processes is the default method, threading is supported as well. Running tests +in parallel reduces the time it takes your entire test suite to run. ### Parallel Testing with Processes -The default parallelization method is to fork processes using Ruby's DRb system. The processes -are forked based on the number of workers provided. The default number is the actual core count -on the machine you are on, but can be changed by the number passed to the parallelize method. +The default parallelization method is to fork processes using Ruby's DRb system. +The processes are forked based on the number of workers provided. The default +number is the actual core count on the machine you are on, but can be changed by +the number passed to the parallelize method. To enable parallelization add the following to your `test_helper.rb`: @@ -2267,27 +2584,32 @@ class ActiveSupport::TestCase end ``` -The number of workers passed is the number of times the process will be forked. You may want to -parallelize your local test suite differently from your CI, so an environment variable is provided -to be able to easily change the number of workers a test run should use: +The number of workers passed is the number of times the process will be forked. +You may want to parallelize your local test suite differently from your CI, so +an environment variable is provided to be able to easily change the number of +workers a test run should use: ```bash $ PARALLEL_WORKERS=15 bin/rails test ``` -When parallelizing tests, Active Record automatically handles creating a database and loading the schema into the database for each -process. The databases will be suffixed with the number corresponding to the worker. For example, if you -have 2 workers the tests will create `test-database-0` and `test-database-1` respectively. +When parallelizing tests, Active Record automatically handles creating a +database and loading the schema into the database for each process. The +databases will be suffixed with the number corresponding to the worker. For +example, if you have 2 workers the tests will create `test-database-0` and +`test-database-1` respectively. -If the number of workers passed is 1 or fewer the processes will not be forked and the tests will not -be parallelized and they will use the original `test-database` database. +If the number of workers passed is 1 or fewer the processes will not be forked +and the tests will not be parallelized and they will use the original +`test-database` database. -Two hooks are provided, one runs when the process is forked, and one runs before the forked process is closed. -These can be useful if your app uses multiple databases or performs other tasks that depend on the number of -workers. +Two hooks are provided, one runs when the process is forked, and one runs before +the forked process is closed. These can be useful if your app uses multiple +databases or performs other tasks that depend on the number of workers. -The `parallelize_setup` method is called right after the processes are forked. The `parallelize_teardown` method -is called right before the processes are closed. +The `parallelize_setup` method is called right after the processes are forked. +The `parallelize_teardown` method is called right before the processes are +closed. ```ruby class ActiveSupport::TestCase @@ -2303,14 +2625,17 @@ class ActiveSupport::TestCase end ``` -These methods are not needed or available when using parallel testing with threads. +These methods are not needed or available when using parallel testing with +threads. ### Parallel Testing with Threads -If you prefer using threads or are using JRuby, a threaded parallelization option is provided. The threaded -parallelizer is backed by Minitest's `Parallel::Executor`. +If you prefer using threads or are using JRuby, a threaded parallelization +option is provided. The threaded parallelizer is backed by Minitest's +`Parallel::Executor`. -To change the parallelization method to use threads over forks put the following in your `test_helper.rb`: +To change the parallelization method to use threads over forks put the following +in your `test_helper.rb`: ```ruby class ActiveSupport::TestCase @@ -2318,9 +2643,12 @@ class ActiveSupport::TestCase end ``` -Rails applications generated from JRuby or TruffleRuby will automatically include the `with: :threads` option. +Rails applications generated from JRuby or TruffleRuby will automatically +include the `with: :threads` option. -NOTE: As in the section above, you can also use the environment variable `PARALLEL_WORKERS` in this context, to be able to change the number of workers your test run should use. +NOTE: As in the section above, you can also use the environment variable +`PARALLEL_WORKERS` in this context, to be able to change the number of workers +your test run should use. ### Testing Parallel Transactions @@ -2347,8 +2675,8 @@ create as changes are not automatically rolled back after the test completes. ### Threshold to parallelize tests Running tests in parallel adds an overhead in terms of database setup and -fixture loading. Because of this, Rails won't parallelize executions that involve -fewer than 50 tests. +fixture loading. Because of this, Rails won't parallelize executions that +involve fewer than 50 tests. You can configure this threshold in your `test.rb`: @@ -2367,26 +2695,32 @@ end Testing Eager Loading --------------------- -Normally, applications do not eager load in the `development` or `test` environments to speed things up. But they do in the `production` environment. +Normally, applications do not eager load in the `development` or `test` +environments to speed things up. But they do in the `production` environment. -If some file in the project cannot be loaded for whatever reason, it is important to detect it before deploying to production. +If some file in the project cannot be loaded for whatever reason, it is +important to detect it before deploying to production. ### Continuous Integration -If your project has CI in place, eager loading in CI is an easy way to ensure the application eager loads. +If your project has CI in place, eager loading in CI is an easy way to ensure +the application eager loads. -CIs typically set an environment variable to indicate the test suite is running there. For example, it could be `CI`: +CIs typically set an environment variable to indicate the test suite is running +there. For example, it could be `CI`: ```ruby # config/environments/test.rb config.eager_load = ENV["CI"].present? ``` -Starting with Rails 7, newly generated applications are configured that way by default. +Starting with Rails 7, newly generated applications are configured that way by +default. ### Bare Test Suites -If your project does not have continuous integration, you can still eager load in the test suite by calling `Rails.application.eager_load!`: +If your project does not have continuous integration, you can still eager load +in the test suite by calling `Rails.application.eager_load!`: #### Minitest @@ -2417,11 +2751,16 @@ Additional Testing Resources ### Errors -In system tests, integration tests and functional controller tests, Rails will attempt to rescue from errors raised and respond with HTML error pages by default. This behavior can be controlled by the [`config.action_dispatch.show_exceptions`](/configuring.html#config-action-dispatch-show-exceptions) configuration. +In system tests, integration tests and functional controller tests, Rails will +attempt to rescue from errors raised and respond with HTML error pages by +default. This behavior can be controlled by the +[`config.action_dispatch.show_exceptions`](/configuring.html#config-action-dispatch-show-exceptions) +configuration. ### Testing Time-Dependent Code -Rails provides built-in helper methods that enable you to assert that your time-sensitive code works as expected. +Rails provides built-in helper methods that enable you to assert that your +time-sensitive code works as expected. The following example uses the [`travel_to`][travel_to] helper: @@ -2440,7 +2779,10 @@ end assert_equal Date.new(2004, 10, 24), user.activation_date ``` -Please see [`ActiveSupport::Testing::TimeHelpers`][time_helpers_api] API reference for more information about the available time helpers. +Please see [`ActiveSupport::Testing::TimeHelpers`][time_helpers_api] API +reference for more information about the available time helpers. -[travel_to]: https://api.rubyonrails.org/classes/ActiveSupport/Testing/TimeHelpers.html#method-i-travel_to -[time_helpers_api]: https://api.rubyonrails.org/classes/ActiveSupport/Testing/TimeHelpers.html +[travel_to]: + https://api.rubyonrails.org/classes/ActiveSupport/Testing/TimeHelpers.html#method-i-travel_to +[time_helpers_api]: + https://api.rubyonrails.org/classes/ActiveSupport/Testing/TimeHelpers.html From 9099b7dcd1db24197b9d5e940bf34646a56f55e4 Mon Sep 17 00:00:00 2001 From: harriet oughton Date: Thu, 21 Nov 2024 20:19:39 +0000 Subject: [PATCH 14/31] Apply changes to section 2.1 --- guides/source/testing.md | 23 ++++++----------------- 1 file changed, 6 insertions(+), 17 deletions(-) diff --git a/guides/source/testing.md b/guides/source/testing.md index e402015c3d6b9..88c978ceeb391 100644 --- a/guides/source/testing.md +++ b/guides/source/testing.md @@ -17,41 +17,30 @@ After reading this guide, you will know: Why Write Tests? ---------------- -Rails makes it super easy to write your tests. It starts by producing skeleton -test code when you create your models and controllers. +Writing automated tests can be a faster way of ensuring your code continues to work as expected than manual testing through the browser or the console. Failing tests can quickly reveal issues, allowing you to identify and fix bugs early in the development process. This practice not only improves the reliability of your code but also improves confidence in your changes. -By running your Rails tests you can quickly and easily ensure your code still -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 view the output through your browser. +Rails makes it easy to write tests. You can read more about Rails' built in support for testing in the next section. Introduction to Testing ----------------------- -Testing was woven into the Rails fabric from the very beginning, and is central +With Rails, testing is central to the development process right from the creation of a new application. ### Test Setup 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: +then you will see: ```bash $ ls -F test -application_system_test_case.rb controllers/ helpers/ mailers/ system/ -channels/ fixtures/ integration/ models/ test_helper.rb +application_system_test_case.rb controllers/ helpers/ mailers/ system/ fixtures/ integration/ models/ test_helper.rb ``` ### Test Directories -The `helpers`, `mailers`, and `models` directories are where tests for view -helpers, mailers, and models respectively should be stored. The `channels` -directory is where tests for Action Cable connection and channels should be -stored. The `controllers` directory is where tests for controllers, routes, and -views should be stored. The `integration` directory is where tests for -interactions between controllers should be stored. +The `helpers`, `mailers`, and [`models`](#model-testing) directories store tests for view helpers, mailers, and models, respectively. The [`controllers`](#functional-testing-for-controllers) directory is used for tests related to controllers, routes, and views, where http requests will be simulated and assertions made on the outcomes. The [`integration`](#integration-testing) directory is reserved for tests that cover 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 From 2660edb6bafba5b289490dac539cee8f54e60708 Mon Sep 17 00:00:00 2001 From: harriet oughton Date: Thu, 28 Nov 2024 19:54:14 +0000 Subject: [PATCH 15/31] Apply changes from 2.1 to 2.4.1 --- guides/source/testing.md | 27 +++++++++++---------------- 1 file changed, 11 insertions(+), 16 deletions(-) diff --git a/guides/source/testing.md b/guides/source/testing.md index 88c978ceeb391..6ec18d58be38b 100644 --- a/guides/source/testing.md +++ b/guides/source/testing.md @@ -42,16 +42,14 @@ application_system_test_case.rb controllers/ helpers/ The `helpers`, `mailers`, and [`models`](#model-testing) directories store tests for view helpers, mailers, and models, respectively. The [`controllers`](#functional-testing-for-controllers) directory is used for tests related to controllers, routes, and views, where http requests will be simulated and assertions made on the outcomes. The [`integration`](#integration-testing) directory is reserved for tests that cover interactions between controllers. -The system test directory holds system tests, which are used for full browser +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. +tests inherit from [Capybara](https://github.com/teamcapybara/capybara) and perform in-browser tests for your application. -Fixtures are a way of organizing test data; they can be stored in the `fixtures` -directory. +[Fixtures](https://api.rubyonrails.org/v3.1/classes/ActiveRecord/Fixtures.html) are a way of mocking up data to use in your tests, so that you don't have to use 'real' data. They are stored in the `fixtures` directory, and you can read more about them in the [Fixtures](#fixtures) section below. -A `jobs` directory will also be created when an associated test is first -generated. +A `jobs` directory will also be created for your job tests when you first [generate a job](active_job_basics.html#create-the-job). The `test_helper.rb` file holds the default configuration for your tests. @@ -103,9 +101,7 @@ 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. +Requiring the file, `test_helper.rb`, loads the default configuration to run tests. All methods added to this file are also available in tests when this file is included. ```ruby class ArticleTest < ActiveSupport::TestCase @@ -115,7 +111,7 @@ end This is called a test case, because the `ArticleTest` class inherits from `ActiveSupport::TestCase`. It therefore also has all the methods from -`ActiveSupport::TestCase` available to it. Later in this guide, we'll see some +`ActiveSupport::TestCase` available to it. [Later in this guide](#assertions-in-our-test-cases), we'll see some of the methods this gives us. Any method defined within a class inherited from `Minitest::Test` (which is the @@ -124,8 +120,7 @@ called a test. So, methods defined as `test_password` and `test_valid_password` are 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: +a standard `Minitest::Unit` test with method names prefixed with `test_`, allowing you to focus on writing the test logic without having to think about naming the methods. For example, you can write: ```ruby test "the truth" do @@ -145,10 +140,10 @@ Although you can still use regular method definitions, using the `test` macro allows for a more readable test name. 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. +result does not need to be a valid Ruby identifier, as Ruby allows any string to serve +as a method name, including those containing punctuation characters. While this +may require using `define_method` and `send` to define and invoke such +methods, there are few formal restrictions on the names themselves. Next, let's look at our first assertion: From c6d30280c86d65b7614fbb0199302e422c362dbd Mon Sep 17 00:00:00 2001 From: harriet oughton Date: Fri, 29 Nov 2024 17:43:57 +0000 Subject: [PATCH 16/31] Apply changes from 2.4.1 to Section 5 --- guides/source/testing.md | 100 ++++++++++++++++++--------------------- 1 file changed, 46 insertions(+), 54 deletions(-) diff --git a/guides/source/testing.md b/guides/source/testing.md index 6ec18d58be38b..dd2c2502cca62 100644 --- a/guides/source/testing.md +++ b/guides/source/testing.md @@ -166,8 +166,9 @@ the test pass. #### 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. Here, we are asserting that the article will not -save, which will fail the test when the article saves successfully. +`article_test.rb` test case. In this example, we assert that the article will +not save without meeting certain criteria; hence, if the article saves +successfully, the test will fail, demonstrating a test failure. ```ruby test "should not save article without title" do @@ -176,7 +177,7 @@ test "should not save article without title" do end ``` -Let us run this newly added test (where `6` is the line number where the test is +Let us run this newly added test (with `6` being the line number where the test is defined). ```bash @@ -202,13 +203,11 @@ 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: +In the output, `F` indicates a test failure. The trace under `Failure` includes the name of the failing test, +followed by a stack trace and a message showing the actual value and the expected value from the +assertion. The default assertion messages offer just enough information to help identify the error. +For improved readability, every assertion allows an optional message parameter to customize the failure +message, as shown below: ```ruby test "should not save article without title" do @@ -259,7 +258,7 @@ 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). -#### Encountering and Asserting Error-Presence +#### Reporting Errors To see how an error gets reported, here's a test containing an error: @@ -297,8 +296,8 @@ 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 green dot above -the 'finished' line denotes the one passing test. +Notice the 'E' in the output. It denotes a test with an error. The green dot above +the 'Finished' line denotes the one passing test. 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 @@ -306,10 +305,10 @@ 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 +When a test fails you are presented with the corresponding backtrace. By default, +Rails filters the backtrace and will only print lines relevant to your +application. This eliminates noise and helps you to focus on your +code. However, in situations when you want to see the full backtrace, set the `-b` (or `--backtrace`) argument to enable this behavior: ```bash @@ -340,7 +339,7 @@ Assertions are the worker bees of testing. They are the ones that actually perform the checks to ensure that things are going as planned. Here's an extract of the assertions you can use with -[`Minitest`](https://github.com/minitest/minitest), the default testing library +[`minitest`](https://github.com/minitest/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. @@ -380,16 +379,15 @@ specify to make your test failure messages clearer. | `assert_no_error_reported { block }` | Ensures that no errors have been reported, e.g. `assert_no_error_reported { perform_service }`| | `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 the [Minitest API +The above are a subset of assertions that minitest supports. For an exhaustive and +more up-to-date list, please check the [minitest API documentation](http://docs.seattlerb.org/minitest/Minitest), specifically [`Minitest::Assertions`](http://docs.seattlerb.org/minitest/Minitest/Assertions.html). -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 +With minitest you can add 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 +NOTE: Creating your own assertions is a topic that we won't cover in this guide. ### Rails-Specific Assertions @@ -404,7 +402,7 @@ Rails adds some custom assertions of its own to the `minitest` framework: | [`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_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 extra 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_routing(expected_path, options, defaults={}, extras = {}, message=nil)`][] | Asserts that `path` and `options` match both ways; in other words, it verifies that `path` generates `options` and then that `options` generates `path`. This essentially combines `assert_recognizes` and `assert_generates` into one step. The extras hash allows you to specify options that would normally be provided as a query string to the action. The message parameter allows you to specify a custom error message to display upon failure.| | [`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](https://rubydoc.info/gems/rack/Rack/Utils#HTTP_STATUS_CODES-constant) and how their [mapping](https://rubydoc.info/gems/rack/Rack/Utils#SYMBOL_TO_STATUS_CODE-constant) 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`.| @@ -446,7 +444,7 @@ Rails adds some custom assertions of its own to the `minitest` framework: You'll see the usage of some of these assertions in the next chapter. -### Assertions in Our Test Cases +### Assertions in 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 @@ -461,15 +459,15 @@ cases. In fact, Rails provides the following classes for you to inherit from: * [`Rails::Generators::TestCase`](https://api.rubyonrails.org/classes/Rails/Generators/TestCase.html) Each of these classes include `Minitest::Assertions`, allowing us to use all of -the basic assertions in our tests. +the basic assertions in your tests. -NOTE: For more information on `Minitest`, refer to its +NOTE: For more information on `minitest`, refer to the [documentation](http://docs.seattlerb.org/minitest). ### Transactions By default, Rails automatically wraps tests in a database transaction that is -rolled back after they finish. This makes tests independent of each other and +rolled back once completed. This makes tests independent of each other and means that changes to the database are only visible within a single test. ```ruby @@ -482,12 +480,12 @@ class MyTest < ActiveSupport::TestCase end ``` -The method `ActiveRecord::Base.current_transaction` still acts as intended, +The method [`ActiveRecord::Base.current_transaction`](https://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html#method-i-current_transaction) still acts as intended, though: ```ruby class MyTest < ActiveSupport::TestCase - test "current_transaction" do + test "Active Record current_transaction method works as expected" do # The implicit transaction around tests does not interfere with the # application-level semantics of the current_transaction. assert User.current_transaction.blank? @@ -514,8 +512,7 @@ end 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. +Or we can run a single test file by appending the filename to the `bin/rails test` command. ```bash $ bin/rails test test/models/article_test.rb @@ -570,7 +567,7 @@ $ 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 +showing verbose progress, and so on. Check the documentation of the test runner as follows: ```bash @@ -619,13 +616,9 @@ Known extensions: rails, pride The Test Database ----------------- -Just about every Rails application interacts heavily with a database and, as a -result, your tests will need a database to interact with as well. To write -efficient tests, you'll need to understand how to set up this database and -populate it with sample data. +Just about every Rails application interacts heavily with a database and so your tests will need a database to interact with as well. This section covers how to set up this test database and populate it with sample data. -By default, every Rails application has three environments: development, test, -and production. The database for each one of them is configured in +As mentioned in the [Test Envionment section](#the-test-environment), every Rails application has three environments: development, test, and production. The database for each one of them is configured in `config/database.yml`. A dedicated test database allows you to set up and interact with test data in @@ -634,12 +627,12 @@ without worrying about the data in the development or production databases. ### Maintaining the Test Database Schema -In order to run your tests, your test database will need to have the current -structure. The test helper checks whether your test database has any pending +In order to run your tests, your test database needs the current +schema. The test helper checks whether your test database has any pending migrations. 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/rails db:migrate`) will bring +migrations against the development database (using `bin/rails db:migrate`) will bring the schema up to date. NOTE: If there were modifications to existing migrations, the test database @@ -662,7 +655,7 @@ NOTE: Fixtures are not designed to create every object that your tests need, and are best managed when only used for default data that can be applied to the common case. -Fixtures can be stored in your `test/fixtures` directory. +Fixtures are stored in your `test/fixtures` directory. #### YAML @@ -688,7 +681,7 @@ Each fixture is given a name followed by an indented list of colon-separated key/value pairs. Records are typically separated by a blank line. You can place comments in a fixture file by using the # character in the first column. -If you are working with [associations](/association_basics.html), you can define +If you are working with [associations](association_basics.html), you can define a reference node between two different fixtures. Here's an example with a `belongs_to`/`has_many` association: @@ -747,7 +740,7 @@ first: title: An Article ``` -Assuming that there is an image/png encoded file at +Assuming that there is an [image/png][] encoded file at `test/fixtures/files/first.png`, the following YAML fixture entries will generate the related `ActiveStorage::Blob` and `ActiveStorage::Attachment` records: @@ -768,7 +761,7 @@ first_thumbnail_attachment: [image/png]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types#image_types -#### ERB and Fixtures +#### Embedding Code in Fixtures 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 @@ -794,17 +787,16 @@ default. Loading involves three steps: 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 +are getting permission errors on running tests, make sure the database user has the permission to disable these triggers in the testing environment. (In PostgreSQL, only superusers can disable all triggers. Read more about -PostgreSQL permissions -[here](https://www.postgresql.org/docs/current/sql-altertable.html)). +[permissions in the PostgreSQL docs](https://www.postgresql.org/docs/current/sql-altertable.html)). #### Fixtures are Active Record Objects Fixtures are instances of Active Record. As mentioned 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: +local to the test case. For example: ```ruby # this will return the User object for the fixture named david @@ -813,7 +805,7 @@ users(:david) # this will return the property for david called id users(:david).id -# methods available on the User class can also be accessed +# methods available to the User class can also be accessed david = users(:david) david.call(david.partner) ``` @@ -830,7 +822,7 @@ users(:david, :steve) Model Testing ------------- -Model tests are used to test the various models of your application and their +Model tests are used to test the models of your application and their associated logic. You can test this logic using the assertions and fixtures that we've explored in the sections above. @@ -1847,7 +1839,7 @@ end If your application uses Ruby >= 3.0 or higher, depends on [Nokogiri >= 1.14.0](https://github.com/sparklemotion/nokogiri/releases/tag/v1.14.0) or -higher, and depends on [Minitest >= +higher, and depends on [minitest >= >5.18.0](https://github.com/minitest/minitest/blob/v5.18.0/History.rdoc#5180--2023-03-04-), `document_root_element` supports [Ruby's Pattern Matching](https://docs.ruby-lang.org/en/master/syntax/pattern_matching_rdoc.html): @@ -2615,7 +2607,7 @@ threads. ### Parallel Testing with Threads If you prefer using threads or are using JRuby, a threaded parallelization -option is provided. The threaded parallelizer is backed by Minitest's +option is provided. The threaded parallelizer is backed by minitest's `Parallel::Executor`. To change the parallelization method to use threads over forks put the following From 8a07e56558388c20473c4d529ee8e8c85fbf09cf Mon Sep 17 00:00:00 2001 From: harriet oughton Date: Wed, 4 Dec 2024 18:42:09 +0000 Subject: [PATCH 17/31] Apply changes from Section 5 onwards --- guides/source/testing.md | 195 ++++++++++++++++----------------------- 1 file changed, 80 insertions(+), 115 deletions(-) diff --git a/guides/source/testing.md b/guides/source/testing.md index dd2c2502cca62..1998d0c27bc38 100644 --- a/guides/source/testing.md +++ b/guides/source/testing.md @@ -462,7 +462,7 @@ Each of these classes include `Minitest::Assertions`, allowing us to use all of the basic assertions in your tests. NOTE: For more information on `minitest`, refer to the -[documentation](http://docs.seattlerb.org/minitest). +[minitest documentation](http://docs.seattlerb.org/minitest). ### Transactions @@ -841,12 +841,7 @@ Instead, they inherit from Functional Testing for Controllers ---------------------------------- -In Rails, a focus on 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 focusing on testing how your actions -handle the requests and the expected result or response. Functional controller +When writing functional tests, you are focusing on testing how controller actions handle the requests and the expected result or response. Functional controller tests are sometimes used in cases where system tests are not appropriate, e.g., to confirm an API response. @@ -947,8 +942,7 @@ post articles_path, params: { article: { title: "Ahoy!" } }, as: :json ``` NOTE: If you try running the `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. +`articles_controller_test.rb` it will (correctly) fail due to the newly added model-level validation. Let us modify the `test_should_create_article` test in `articles_controller_test.rb` so that this test passes: @@ -973,7 +967,7 @@ 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") } ``` -### Available Request Types for Functional Tests +### HTTP 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: @@ -986,19 +980,16 @@ request. There are 6 request types supported in Rails functional tests: * `delete` All of the 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` most -often. +C.R.U.D. application you'll be using `post`, `get`, `put`, and `delete` most often. 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. +accepted by the action; instead, they focus on the result. For testing the request type, request tests are available, making your tests more purposeful. ### Testing XHR (Ajax) Requests -An AJAX request (Asynchronous Javscript and XML) is a type of request where -information is sent over a server without the page reloading. To test Ajax -requests, you can specify the `xhr: true` option to `get`, `post`, `patch`, -`put`, and `delete` methods. For example: +An AJAX request (Asynchronous Javscript and XML) is a technique where content is fetched from the server using asynchronous HTTP requests and the relevant parts of the page are updated without requiring a full page load. + +To test Ajax requests, you can specify the `xhr: true` option to `get`, `post`, `patch`, `put`, and `delete` methods. For example: ```ruby test "ajax request" do @@ -1038,7 +1029,6 @@ a request is made: * `@request` - The request object * `@response` - The response object - ```ruby class ArticlesControllerTest < ActionDispatch::IntegrationTest test "should get index" do @@ -1069,7 +1059,7 @@ get articles_url, headers: { "HTTP_REFERER": "http://example.com/home" } # simul ### Testing `flash` Notices -As we have seen in the secctions above, one of the three hash objects we have +As we have seen in the [sections above](#testing-other-request-objects), one of the three hash objects we have access to is `flash`. We want to add a `flash` message to our blog application whenever someone @@ -1128,7 +1118,7 @@ def create end ``` -Now if we run our tests, we should see it pass: +Now, if we run our tests, we should see it pass: ```bash $ bin/rails test test/controllers/articles_controller_test.rb -n test_should_create_article @@ -1147,7 +1137,7 @@ Finished in 0.081972s, 12.1993 runs/s, 48.7972 assertions/s. NOTE: If you generated your controller using the scaffold generator, the flash message will already be implemented in your `create` action. -### Putting It Together +### Tests for `show`, `update`, and `delete` Actions At this point we have looked at tests for the `:index` as well as the`:create` action. What about the other actions? @@ -1162,13 +1152,13 @@ test "should show article" do end ``` -If you remember from our discussion earlier on fixtures, the `articles()` method -will give us access to our articles fixtures. +If you remember from our discussion earlier on [fixtures](#fixtures), the `articles()` method +will give us access to the articles fixtures. How about deleting an existing article? ```ruby -test "should destroy article" do +test "should delete article" do article = articles(:one) assert_difference("Article.count", -1) do delete article_url(article) @@ -1178,7 +1168,7 @@ test "should destroy article" do end ``` -We can also consider a test for updating an existing article. +Let's also consider a test for updating an existing article. ```ruby test "should update article" do @@ -1193,12 +1183,12 @@ test "should update article" do end ``` -Notice we're starting to see some duplication in these three tests, they both -access the same article fixture data. It is possible to D.R.Y. this up ('Don't -Repeat Yourself') by using the `setup` and `teardown` methods provided by +Notice that there is some duplication in these three tests - they both +access the same article fixture data. It is possible to D.R.Y. ('Don't +Repeat Yourself') the implementation by using the `setup` and `teardown` methods provided by `ActiveSupport::Callbacks`. -Our tests now might look something like the below. +The tests might look like this: ```ruby require "test_helper" @@ -1241,15 +1231,14 @@ end ``` NOTE: 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. +can also accept a block, lambda, or a method name as a symbol to be called. Integration Testing ------------------- -Integration tests take functional controller tests one step further, as they are -focussed on testing how various parts of our application interact. They are +Integration tests take functional controller tests one step further - they focus on testing how various parts of our application interact, and are generally used to test important workflows within our application. Rails -integration tests can be stored in the `test/integration` directory. +integration tests are stored in the `test/integration` directory. Rails provides a generator to create an integration test skeleton for us. @@ -1271,25 +1260,24 @@ class UserFlowsTest < ActionDispatch::IntegrationTest end ``` -Here the test is inheriting from `ActionDispatch::IntegrationTest`. This makes -some additional [helpers](testing.html#helpers-available-for-integration-tests) -available for us to use in our integration tests, alongside the standard testing +Here the test is inheriting from [`ActionDispatch::IntegrationTest`](https://api.rubyonrails.org/classes/ActionDispatch/IntegrationTest.html). This makes +some additional [helpers available for integration tests](testing.html#helpers-available-for-integration-tests) alongside the standard testing helpers. ### 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 +Let's add an integration test to our blog application, by starting 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: +Start by generating the 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 we should see: +It should have created a test file placeholder. With the output of the +previous command you should see: ``` invoke test_unit @@ -1304,23 +1292,23 @@ require "test_helper" class BlogFlowTest < ActionDispatch::IntegrationTest test "can see the welcome page" do get "/" - assert_dom "h1", "Welcome#index" + assert_selector "h1", "Welcome#index" end end ``` -We will take a look at `assert_dom` to query the resulting HTML of a request in +Let's take a look at `assert_selector` to query the resulting HTML of a request in the [Testing Views](#testing-views) section below. It is used for testing the -response of our request by asserting the presence of key HTML elements and their +response of the 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 +If you visit the root path, you should see `welcome/index.html.erb` rendered for the view. So this assertion should pass. #### Creating Articles Integration -We can also test our ability to create a new article in our blog and display the -resulting article. +To test the ability to create a new article in our blog and display the +resulting article, see the example below: ```ruby test "can create an article" do @@ -1336,13 +1324,11 @@ test "can create an article" do end ``` -Let's break this test down so we can understand it. +Let's break this test down: -We start by calling the `:new` action on our Articles controller. This response -should be successful. +The `:new` action of our Articles controller is called first, and the response should be successful. -After this we make a post request to the `:create` action of our Articles -controller: +Next, a `post` request is made to the `:create` action of the Articles controller: ```ruby post "/articles", @@ -1351,51 +1337,37 @@ assert_response :redirect follow_redirect! ``` -The two lines following the request are to handle the redirect we setup when -creating a new article. +The two lines following the request are to handle the redirect 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. -Finally we can assert that our response was successful and our new article is -readable on the page. - -#### Taking It Further +Finally it can be asserted that the response was successful and the newly-created article is readable on the page. -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 adding comments, editing comments or removing articles. Integration tests -are a great place to experiment with all kinds of use cases for our -applications. +A very small workflow for visiting our blog +and creating a new article was successfully tested above. To extend this, additional tests could be added for features like adding comments, editing comments or removing articles. Integration tests +are a great place to experiment with all kinds of use cases for our applications. ### Helpers Available for Integration Tests -Here are some of the other helpers we can choose from in our integration tests. +There are numerous helpers to choose from to aid in the integration tests. Some include: -For dealing with the integration test runner, see -[`ActionDispatch::Integration::Runner`](https://api.rubyonrails.org/classes/ActionDispatch/Integration/Runner.html). +* [`ActionDispatch::Integration::Runner`](https://api.rubyonrails.org/classes/ActionDispatch/Integration/Runner.html) for helpers relating to the integration test runner, including creating a new session. -When performing requests, we will have -[`ActionDispatch::Integration::RequestHelpers`](https://api.rubyonrails.org/classes/ActionDispatch/Integration/RequestHelpers.html) -available for our use. +* [`ActionDispatch::Integration::RequestHelpers`](https://api.rubyonrails.org/classes/ActionDispatch/Integration/RequestHelpers.html) for performing requests. -If we need to upload files, take a look at -[`ActionDispatch::TestProcess::FixtureFile`](https://api.rubyonrails.org/classes/ActionDispatch/TestProcess/FixtureFile.html) -to help. +* [`ActionDispatch::TestProcess::FixtureFile`](https://api.rubyonrails.org/classes/ActionDispatch/TestProcess/FixtureFile.html) for uploading files. -If we need to modify the session, or state of our integration test, take a look -at -[`ActionDispatch::Integration::Session`](https://api.rubyonrails.org/classes/ActionDispatch/Integration/Session.html) -to help. +* [`ActionDispatch::Integration::Session`](https://api.rubyonrails.org/classes/ActionDispatch/Integration/Session.html) to modify sessions or the state of the integration tests. System Testing -------------- -Similarly to integration testing, system testing also allows you to test how the +Similarly to integration testing, system testing allows you to test how the components of your app work together, but from the point of view of a user. It does this by running tests in either a real or a headless browser (a browser which runs in the background without opening a visible window). System tests use -Capybara under the hood. +[Capybara](https://www.rubydoc.info/github/jnicklas/capybara) under the hood. For creating Rails system tests, you use the `test/system` directory in your application. Rails provides a generator to create a system test skeleton for @@ -1435,9 +1407,8 @@ When you generate a new application or scaffold, an where all the configuration for your system tests should live. If you want to change the default settings, you can change what the system tests -are "driven by". Say you want to change the driver from Selenium to Cuprite. -First add the `cuprite` gem to your `Gemfile`. Then in your -`application_system_test_case.rb` file do the following: +are "driven by". If you want to change the driver from Selenium to Cuprite, you'd add the `cuprite` gem to your `Gemfile`. Then in your +`application_system_test_case.rb` file you'd do the following: ```ruby require "test_helper" @@ -1498,7 +1469,7 @@ Now you should get a connection to the remote browser. $ SELENIUM_REMOTE_URL=http://localhost:4444/wd/hub bin/rails test:system ``` -If your application in test is running remote too, e.g. within a Docker +If your application is remote, e.g. within a Docker container, Capybara needs more input about how to [call remote servers](https://github.com/teamcapybara/capybara#calling-remote-servers). @@ -1506,10 +1477,10 @@ servers](https://github.com/teamcapybara/capybara#calling-remote-servers). require "test_helper" class ApplicationSystemTestCase < ActionDispatch::SystemTestCase - def setup + def setup do Capybara.server_host = "0.0.0.0" # bind to all interfaces Capybara.app_host = "http://#{IPSocket.getaddress(Socket.gethostname)}" if ENV["SELENIUM_REMOTE_URL"].present? - super + end end # ... end @@ -1519,7 +1490,7 @@ Now you should get a connection to a remote browser and server, regardless if it is running in a Docker container or CI. If your Capybara configuration requires more setup than provided by Rails, this -additional configuration could be added into the +additional configuration can be added into the `application_system_test_case.rb` file. Please see [Capybara's @@ -1528,8 +1499,8 @@ settings. ### Implementing a System Test -Now we're going to add a system test to our blog application. We'll demonstrate -writing a system test by visiting the index page and creating a new blog +Next a system test will be added to the blog application. This example will demonstrate how to +write a system test by visiting the index page and creating a new blog article. If you used the scaffold generator, a system test skeleton was automatically @@ -1540,7 +1511,7 @@ system test skeleton. $ bin/rails generate system_test articles ``` -It should have created a test file placeholder for us. With the output of the +It should have created a test file placeholder. With the output of the previous command you should see: ``` @@ -1548,7 +1519,7 @@ previous command you should see: create test/system/articles_test.rb ``` -Now let's open that file and write our first assertion: +Now, let's open that file and write the first assertion: ```ruby require "application_system_test_case" @@ -1600,16 +1571,16 @@ index page. This will redirect the browser to `/articles/new`. Then the test will fill in the title and body of the article with the specified text. Once the fields are filled in, "Create Article" is clicked on which will -send a POST request to create the new article in the database. +send a POST request to `/articles/create`. We will be redirected back to the articles index page and there we assert that the text from the new article's title is on the articles index page. #### Testing for Multiple Screen Sizes -If you want to test for mobile sizes on top of testing for desktop, you can +If you want to test for mobile sizes in addition to testing for desktop, you can create another class that inherits from `ActionDispatch::SystemTestCase` and use -it in your test suite. In this example a file called +it in your test suite. In this example, a file called `mobile_system_test_case.rb` is created in the `/test` directory with the following configuration. @@ -1655,16 +1626,15 @@ take a screenshot of the browser. The beauty of system testing is that it is similar to [integration testing](#integration-testing) in that it tests the user's interaction with your -controller, model, and view, but system testing is much more robust and actually +controller, model, and view, but system testing tests your application as if a real user were using it. With system tests, you -can test anything that the user themselves would do in your application such as +can test anything that a user would do in your application such as commenting, deleting articles, publishing draft articles, etc. Test Helpers ------------ -To avoid code duplication, you can add your own test helpers. Sign in helper can -be a good example: +To avoid code duplication, you can add your own test helpers. Here is an example for signing in: ```ruby # test/test_helper.rb @@ -1753,9 +1723,7 @@ Testing Routes -------------- Like everything else in your Rails application, you can test your routes. Route -tests reside in `test/controllers/` or are part of controller tests. - -NOTE: If your application has complex routes, Rails provides a number of useful +tests reside in `test/controllers/` or are part of controller tests. If your application has complex routes, Rails provides a number of useful helpers to test them. For more information on routing assertions available in Rails, see the API @@ -1809,16 +1777,15 @@ assert_dom "ol" do end ``` -The `assert_dom_equal` method tests two HTML strings for equivalency, as in the -example below: +The `assert_dom_equal` method compares two HTML strings to see if they are equal: ```ruby assert_dom_equal 'Read more', link_to("Read more", "http://www.further-reading.com") ``` -These assertions are quite powerful. For more advanced usage, refer to their -[documentation](https://github.com/rails/rails-dom-testing). +For more advanced usage, refer to the +[`rails-dom-testing` documentation](https://github.com/rails/rails-dom-testing). In order to integrate with [rails-dom-testing][], tests that inherit from `ActionView::TestCase` declare a `document_root_element` method that returns the @@ -1837,9 +1804,9 @@ test "renders a link to itself" do end ``` -If your application uses Ruby >= 3.0 or higher, depends on [Nokogiri >= +If your application depends on [Nokogiri >= 1.14.0](https://github.com/sparklemotion/nokogiri/releases/tag/v1.14.0) or -higher, and depends on [minitest >= +higher, and [minitest >= >5.18.0](https://github.com/minitest/minitest/blob/v5.18.0/History.rdoc#5180--2023-03-04-), `document_root_element` supports [Ruby's Pattern Matching](https://docs.ruby-lang.org/en/master/syntax/pattern_matching_rdoc.html): @@ -1860,7 +1827,7 @@ end If you'd like to access the same [Capybara-powered Assertions](https://rubydoc.info/github/teamcapybara/capybara/master/Capybara/Minitest/Assertions) -that your [Functional and System Testing](#functional-and-system-testing) tests +that your [System Testing](#system-testing) tests utilize, you can define a base class that inherits from `ActionView::TestCase` and transforms the `document_root_element` into a `page` method: @@ -1963,7 +1930,7 @@ end ### Testing View Partials [Partial](layouts_and_rendering.html#using-partials) templates - usually called -"partials" - are another device for breaking the rendering process into more +"partials" - can break the rendering process into more manageable chunks. With partials, you can extract pieces of code from your templates to separate files and reuse them throughout your templates. @@ -2541,7 +2508,7 @@ which runs all tests including system tests. Parallel Testing ---------------- -Parallel testing allows you to parallelize your test suite. While forking +Running tests in parallel reduces the time it takes your entire test suite to run. While forking processes is the default method, threading is supported as well. Running tests in parallel reduces the time it takes your entire test suite to run. @@ -2549,8 +2516,8 @@ in parallel reduces the time it takes your entire test suite to run. The default parallelization method is to fork processes using Ruby's DRb system. The processes are forked based on the number of workers provided. The default -number is the actual core count on the machine you are on, but can be changed by -the number passed to the parallelize method. +number is the actual core count on the machine, but can be changed by +the number passed to the `parallelize` method. To enable parallelization add the following to your `test_helper.rb`: @@ -2623,7 +2590,7 @@ Rails applications generated from JRuby or TruffleRuby will automatically include the `with: :threads` option. NOTE: As in the section above, you can also use the environment variable -`PARALLEL_WORKERS` in this context, to be able to change the number of workers +`PARALLEL_WORKERS` in this context, to change the number of workers your test run should use. ### Testing Parallel Transactions @@ -2648,7 +2615,7 @@ end NOTE: With disabled transactional tests, you have to clean up any data tests create as changes are not automatically rolled back after the test completes. -### Threshold to parallelize tests +### Threshold to Parallelize tests Running tests in parallel adds an overhead in terms of database setup and fixture loading. Because of this, Rails won't parallelize executions that @@ -2693,8 +2660,6 @@ config.eager_load = ENV["CI"].present? Starting with Rails 7, newly generated applications are configured that way by default. -### Bare Test Suites - If your project does not have continuous integration, you can still eager load in the test suite by calling `Rails.application.eager_load!`: From f9073ae1070013e9ab3be2a57ccbda424553d3bb Mon Sep 17 00:00:00 2001 From: harriet oughton Date: Wed, 4 Dec 2024 18:52:14 +0000 Subject: [PATCH 18/31] Adjust scaffold_controller code --- guides/source/testing.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/guides/source/testing.md b/guides/source/testing.md index 1998d0c27bc38..3f509a33556e8 100644 --- a/guides/source/testing.md +++ b/guides/source/testing.md @@ -858,7 +858,7 @@ The easiest way to see functional tests in action is to generate a controller using the scaffold generator: ```bash -$ bin/rails generate scaffold_controller article title:string body:text +$ bin/rails generate scaffold_controller article ... create app/controllers/articles_controller.rb ... From 170e81782cdfa6a73c8065acc8e182b1477c0d8e Mon Sep 17 00:00:00 2001 From: harriet oughton Date: Thu, 5 Dec 2024 08:14:14 +0000 Subject: [PATCH 19/31] Add example of generated model test file --- guides/source/testing.md | 29 +++++++++++++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) diff --git a/guides/source/testing.md b/guides/source/testing.md index 3f509a33556e8..d2987731cb435 100644 --- a/guides/source/testing.md +++ b/guides/source/testing.md @@ -111,7 +111,7 @@ end This is called a test case, because the `ArticleTest` class inherits from `ActiveSupport::TestCase`. It therefore also has all the methods from -`ActiveSupport::TestCase` available to it. [Later in this guide](#assertions-in-our-test-cases), we'll see some +`ActiveSupport::TestCase` available to it. [Later in this guide](#assertions-in-test-cases), we'll see some of the methods this gives us. Any method defined within a class inherited from `Minitest::Test` (which is the @@ -830,10 +830,23 @@ Rails model tests are stored under the `test/models` directory. Rails provides a generator to create a model test skeleton for you. ```bash -$ bin/rails generate test_unit:model article title:string body:text +$ bin/rails generate test_unit:model article create test/models/article_test.rb ``` +This command will generate the following file: + +```ruby +# article_test.rb +require "test_helper" + +class ArticleTest < ActiveSupport::TestCase + # test "the truth" do + # assert true + # end +end +``` + Model tests don't have their own superclass like `ActionMailer::TestCase`. Instead, they inherit from [`ActiveSupport::TestCase`](https://api.rubyonrails.org/classes/ActiveSupport/TestCase.html). @@ -1607,6 +1620,16 @@ class PostsTest < MobileSystemTestCase end ``` +#### Capybara Assertions + +Here's an extract of the assertions provided by +[`Capybara`](https://rubydoc.info/github/teamcapybara/capybara/master/Capybara/Minitest/Assertions) which can be used in system tests. + +| Assertion | Purpose | +| ---------------------------------------------------------------- | ------- | +| `assert_selector` | Asserts that a given selector is on the page. | + + #### Screenshot Helper The @@ -1860,6 +1883,8 @@ class ArticlePartialTest < ViewPartialTestCase end ``` +More information about the assertions included by Capybara can be found in the [Capybara Assertions](#capybara-assertions) section. + Starting in Action View version 7.1, the `#rendered` helper method returns an object capable of parsing the view partial's rendered content. From bbb9deccc67418d88d1de2bbb7136c74769849f0 Mon Sep 17 00:00:00 2001 From: harriet oughton Date: Thu, 5 Dec 2024 17:07:09 +0000 Subject: [PATCH 20/31] Add Capybara assertions table --- guides/source/testing.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/guides/source/testing.md b/guides/source/testing.md index d2987731cb435..e45c87bf5f2f0 100644 --- a/guides/source/testing.md +++ b/guides/source/testing.md @@ -1627,7 +1627,13 @@ Here's an extract of the assertions provided by | Assertion | Purpose | | ---------------------------------------------------------------- | ------- | -| `assert_selector` | Asserts that a given selector is on the page. | +| `assert_button(locator = nil, **options, &optional_filter_block)`| Checks if the page has a button with the given text, value or id. | +| `assert_current_path(string, **options)` | Asserts that the page has the given path. | +| `assert_field(locator = nil, **options, &optional_filter_block)` | Checks if the page has a form field with the given label, name or id. | +| `assert_link(locator = nil, **options, &optional_filter_block)` | Checks if the page has a link with the given text or id. | +| `assert_selector(*args, &optional_filter_block)` | Asserts that a given selector is on the page. | +| `assert_table(locator = nil, **options, &optional_filter_block` | Checks if the page has a table with the given id or caption. | +| `assert_text(type, text, **options)` | Asserts that the page has the given text content. | #### Screenshot Helper From 9132fccb1c5f7fc8be7b62baf50f6965a230497b Mon Sep 17 00:00:00 2001 From: harriet oughton Date: Thu, 5 Dec 2024 17:34:49 +0000 Subject: [PATCH 21/31] Clarify when to use assert_selector --- guides/source/testing.md | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/guides/source/testing.md b/guides/source/testing.md index e45c87bf5f2f0..b781e6a83fe03 100644 --- a/guides/source/testing.md +++ b/guides/source/testing.md @@ -1310,13 +1310,9 @@ class BlogFlowTest < ActionDispatch::IntegrationTest end ``` -Let's take a look at `assert_selector` to query the resulting HTML of a request in -the [Testing Views](#testing-views) section below. It is used for testing the -response of the request by asserting the presence of key HTML elements and their -content. +If you visit the root path, you should see `welcome/index.html.erb` rendered for the view. So this assertion should pass. -If you visit the root path, you should see `welcome/index.html.erb` rendered for -the view. So this assertion should pass. +NOTE: The assertion `assert_selector` is available in integration tests to check the presence of key HTML elements and their content. It is similar to `assert_dom`, which should be used when [testing views](#testing-views) as outlined in the section below. #### Creating Articles Integration From d3b3f5ffbba53e75350d649a313d78b94f6f4d39 Mon Sep 17 00:00:00 2001 From: harriet oughton Date: Thu, 5 Dec 2024 19:02:47 +0000 Subject: [PATCH 22/31] Make proof-read changes up to section 4 --- guides/source/testing.md | 36 ++++++++++++++++-------------------- 1 file changed, 16 insertions(+), 20 deletions(-) diff --git a/guides/source/testing.md b/guides/source/testing.md index b781e6a83fe03..48366a0cf056f 100644 --- a/guides/source/testing.md +++ b/guides/source/testing.md @@ -40,9 +40,9 @@ application_system_test_case.rb controllers/ helpers/ ### Test Directories -The `helpers`, `mailers`, and [`models`](#model-testing) directories store tests for view helpers, mailers, and models, respectively. The [`controllers`](#functional-testing-for-controllers) directory is used for tests related to controllers, routes, and views, where http requests will be simulated and assertions made on the outcomes. The [`integration`](#integration-testing) directory is reserved for tests that cover interactions between controllers. +The `helpers`, `mailers`, and `models` directories store tests for [view helpers](#testing-view-helpers), [mailers](#testing-mailers), and [models](#model-testing), respectively. The `controllers` directory is used for [tests related to controllers](#functional-testing-for-controllers), routes, and views, where HTTP requests will be simulated and assertions made on the outcomes. The `integration` directory is reserved for [tests that cover interactions between controllers](#integration-testing). -The `system` test directory holds system tests, which are used for full browser +The `system` test directory holds [system tests](#system-testing), 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](https://github.com/teamcapybara/capybara) and perform in-browser tests for your application. @@ -145,7 +145,7 @@ as a method name, including those containing punctuation characters. While this may require using `define_method` and `send` to define and invoke such methods, there are few formal restrictions on the names themselves. -Next, let's look at our first assertion: +This part of a test is called an 'assertion': ```ruby assert true @@ -166,7 +166,7 @@ the test pass. #### 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. In this example, we assert that the article will +`article_test.rb` test case. In this example, it is asserted that the article will not save without meeting certain criteria; hence, if the article saves successfully, the test will fail, demonstrating a test failure. @@ -177,8 +177,8 @@ test "should not save article without title" do end ``` -Let us run this newly added test (with `6` being the line number where the test is -defined). +Here is the output if this newly added test is run (with `6` being the line number where the test is +defined): ```bash $ bin/rails test test/models/article_test.rb:6 @@ -203,7 +203,7 @@ 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` indicates a test failure. The trace under `Failure` includes the name of the failing test, +In the output, `F` indicates a test failure. The section under `Failure` includes the name of the failing test, followed by a stack trace and a message showing the actual value and the expected value from the assertion. The default assertion messages offer just enough information to help identify the error. For improved readability, every assertion allows an optional message parameter to customize the failure @@ -224,7 +224,7 @@ ArticleTest#test_should_not_save_article_without_title [/path/to/blog/test/model Saved the article without a title ``` -To get this test to pass we can add a model level validation for the `title` +To get this test to pass a model-level validation can be added for the `title` field. ```ruby @@ -233,9 +233,8 @@ class Article < ApplicationRecord end ``` -Now the test should pass, as we have not initialized the article in our test -with a `title`, so the model validation will prevent the save. Let us verify by -running the test again: +Now the test should pass, as the article in our test +has not been initialized with a `title`, so the model validation will prevent the save. This can be verified by running the test again: ```bash $ bin/rails test test/models/article_test.rb:6 @@ -253,10 +252,7 @@ Finished in 0.027476s, 36.3952 runs/s, 36.3952 assertions/s. The small green dot displayed means that the test has passed successfully. -NOTE: In that process, 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). +NOTE: In that process, a test was written first which fails for a desired functionality, then after, some code was written which adds the functionality. Finally, the test was run again to ensure it passes. This approach to software development is referred to as _Test-Driven Development_ (TDD). #### Reporting Errors @@ -315,7 +311,7 @@ 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` (so we are +If you want this test to pass you can modify it to use `assert_raises` (so you are now checking for the presence of the error) like so: ```ruby @@ -387,7 +383,7 @@ documentation](http://docs.seattlerb.org/minitest/Minitest), specifically With minitest you can add 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 a topic that we won't cover in +NOTE: Creating your own assertions is a topic that we won't cover in depth in this guide. ### Rails-Specific Assertions @@ -568,7 +564,7 @@ $ bin/rails test test/controllers # run all tests from specific directory The test runner also provides a lot of other features like failing fast, showing verbose progress, and so on. Check the -documentation of the test runner as follows: +documentation of the test runner using the command below: ```bash $ bin/rails test -h @@ -632,7 +628,7 @@ schema. The test helper checks whether your test database has any pending migrations. 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 (using `bin/rails db:migrate`) will bring +migrations (using `bin/rails db:migrate RAILS_ENV=test`) will bring the schema up to date. NOTE: If there were modifications to existing migrations, the test database @@ -715,7 +711,7 @@ Article `first` found in `fixtures/articles.yml` for the latter. NOTE: For associations to reference one another by name, you can use the fixture name instead of specifying the `id:` attribute on the associated fixtures. Rails -will auto assign a primary key to be consistent between runs. For more +will auto-assign a primary key to be consistent between runs. For more information on this association behavior please read the [Fixtures API documentation](https://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html). From e96e7176cff87be0259db58704fd919ec9dfd776 Mon Sep 17 00:00:00 2001 From: harriet oughton Date: Fri, 6 Dec 2024 08:16:08 +0000 Subject: [PATCH 23/31] Make proof-read changes section 4 to 7 --- guides/source/testing.md | 67 ++++++++++++++++++---------------------- 1 file changed, 30 insertions(+), 37 deletions(-) diff --git a/guides/source/testing.md b/guides/source/testing.md index 48366a0cf056f..feaa1904cb6d5 100644 --- a/guides/source/testing.md +++ b/guides/source/testing.md @@ -40,7 +40,7 @@ application_system_test_case.rb controllers/ helpers/ ### Test Directories -The `helpers`, `mailers`, and `models` directories store tests for [view helpers](#testing-view-helpers), [mailers](#testing-mailers), and [models](#model-testing), respectively. The `controllers` directory is used for [tests related to controllers](#functional-testing-for-controllers), routes, and views, where HTTP requests will be simulated and assertions made on the outcomes. The `integration` directory is reserved for [tests that cover interactions between controllers](#integration-testing). +The `helpers`, `mailers`, and `models` directories store tests for [view helpers](#testing-view-helpers), [mailers](#testing-mailers), and [models](#testing-models), respectively. The `controllers` directory is used for [tests related to controllers](#functional-testing-for-controllers), routes, and views, where HTTP requests will be simulated and assertions made on the outcomes. The `integration` directory is reserved for [tests that cover interactions between controllers](#integration-testing). The `system` test directory holds [system tests](#system-testing), which are used for full browser testing of your application. System tests allow you to test your application the @@ -815,8 +815,8 @@ users(:david, :steve) ``` -Model Testing -------------- +Testing Models +-------------- Model tests are used to test the models of your application and their associated logic. You can test this logic using the assertions and fixtures that @@ -923,37 +923,37 @@ The `get` method kicks off the web request and populates the results into the (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. +* `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 +Example: Calling the `:show` action (via a `get` request) for the first `Article`, passing in an `HTTP_REFERER` header: ```ruby 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: +Another example: Calling the `:update` action (via a `patch` request) for the last `Article`, passing in +new text for the `title` in `params`, as an AJAX request: ```ruby patch article_url(Article.last), params: { article: { title: "updated" } }, xhr: true ``` -One more example: Calling the `:create` action to create a new article, passing +One more example: Calling the `:create` action (via a `post` request) to create a new article, passing in text for the `title` in `params`, as JSON request: ```ruby -post articles_path, params: { article: { title: "Ahoy!" } }, as: :json +post articles_url, params: { article: { title: "Ahoy!" } }, as: :json ``` NOTE: If you try running the `test_should_create_article` test from `articles_controller_test.rb` it will (correctly) fail due to the newly added model-level validation. -Let us modify the `test_should_create_article` test in +Now to modify the `test_should_create_article` test in `articles_controller_test.rb` so that this test passes: ```ruby @@ -994,14 +994,14 @@ C.R.U.D. application you'll be using `post`, `get`, `put`, and `delete` most oft NOTE: Functional tests do not verify whether the specified request type is accepted by the action; instead, they focus on the result. For testing the request type, request tests are available, making your tests more purposeful. -### Testing XHR (Ajax) Requests +### Testing XHR (AJAX) Requests An AJAX request (Asynchronous Javscript and XML) is a technique where content is fetched from the server using asynchronous HTTP requests and the relevant parts of the page are updated without requiring a full page load. -To test Ajax requests, you can specify the `xhr: true` option to `get`, `post`, `patch`, `put`, and `delete` methods. For example: +To test AJAX requests, you can specify the `xhr: true` option to `get`, `post`, `patch`, `put`, and `delete` methods. For example: ```ruby -test "ajax request" do +test "AJAX request" do article = articles(:one) get article_url(article), xhr: true @@ -1068,13 +1068,9 @@ get articles_url, headers: { "HTTP_REFERER": "http://example.com/home" } # simul ### Testing `flash` Notices -As we have seen in the [sections above](#testing-other-request-objects), one of the three hash objects we have -access to is `flash`. +As can be seen in the [testing other request objects section](#testing-other-request-objects), one of the three hash objects that is accessible in the tests is `flash`. This section outlines how to test the appearance of a `flash` message in our blog application whenever someone successfully creates a new article. -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: +First, an assertion should be added to the `test_should_create_article` test: ```ruby test "should create article" do @@ -1087,7 +1083,7 @@ test "should create article" do end ``` -If we run our test now, we should see a failure: +If the test is run now, it should fail: ```bash $ bin/rails test test/controllers/articles_controller_test.rb -n test_should_create_article @@ -1111,8 +1107,8 @@ ArticlesControllerTest#test_should_create_article [/test/controllers/articles_co 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: +Now implement the flash message in the controller. The `:create` action +should look like this: ```ruby def create @@ -1127,7 +1123,7 @@ def create end ``` -Now, if we run our tests, we should see it pass: +Now, if the tests are run they should pass: ```bash $ bin/rails test test/controllers/articles_controller_test.rb -n test_should_create_article @@ -1148,10 +1144,10 @@ message will already be implemented in your `create` action. ### Tests for `show`, `update`, and `delete` Actions -At this point we have looked at tests for the `:index` as well as the`:create` -action. What about the other actions? +So far in the guide tests for the `:index` as well as the`:create` +action have been outlined. What about the other actions? -Let's make sure we have a test for `:show`: +You can write a test for `:show` as follows: ```ruby test "should show article" do @@ -1161,8 +1157,7 @@ test "should show article" do end ``` -If you remember from our discussion earlier on [fixtures](#fixtures), the `articles()` method -will give us access to the articles fixtures. +If you remember from our discussion earlier on [fixtures](#fixtures), the `articles()` method will provide access to the articles fixtures. How about deleting an existing article? @@ -1177,7 +1172,7 @@ test "should delete article" do end ``` -Let's also consider a test for updating an existing article. +Here is a test for updating an existing article: ```ruby test "should update article" do @@ -1245,11 +1240,11 @@ can also accept a block, lambda, or a method name as a symbol to be called. Integration Testing ------------------- -Integration tests take functional controller tests one step further - they focus on testing how various parts of our application interact, and are -generally used to test important workflows within our application. Rails +Integration tests take functional controller tests one step further - they focus on testing how several parts of an application interact, and are +generally used to test important workflows. Rails integration tests are stored in the `test/integration` directory. -Rails provides a generator to create an integration test skeleton for us. +Rails provides a generator to create an integration test skeleton as follows: ```bash $ bin/rails generate integration_test user_flows @@ -1293,7 +1288,7 @@ previous command you should see: create test/integration/blog_flow_test.rb ``` -Now let's open that file and write our first assertion: +Now open that file and write the first assertion: ```ruby require "test_helper" @@ -1329,8 +1324,6 @@ test "can create an article" do end ``` -Let's break this test down: - The `:new` action of our Articles controller is called first, and the response should be successful. Next, a `post` request is made to the `:create` action of the Articles controller: @@ -1355,7 +1348,7 @@ are a great place to experiment with all kinds of use cases for our applications ### Helpers Available for Integration Tests -There are numerous helpers to choose from to aid in the integration tests. Some include: +There are numerous helpers to choose from for use in integration tests. Some include: * [`ActionDispatch::Integration::Runner`](https://api.rubyonrails.org/classes/ActionDispatch/Integration/Runner.html) for helpers relating to the integration test runner, including creating a new session. From bd96f0bdb48c915aebf863743b3524f5606edc29 Mon Sep 17 00:00:00 2001 From: harriet oughton Date: Sat, 7 Dec 2024 10:29:22 +0000 Subject: [PATCH 24/31] Make proof-read changes up to section 10 --- guides/source/testing.md | 38 +++++++++++++++++++------------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/guides/source/testing.md b/guides/source/testing.md index feaa1904cb6d5..850e91ce974d4 100644 --- a/guides/source/testing.md +++ b/guides/source/testing.md @@ -1367,9 +1367,8 @@ does this by running tests in either a real or a headless browser (a browser which runs in the background without opening a visible window). System tests use [Capybara](https://www.rubydoc.info/github/jnicklas/capybara) under the hood. -For creating Rails system tests, you use the `test/system` directory in your -application. Rails provides a generator to create a system test skeleton for -you. +Rails system tests are stored in the `test/system` directory in your +application. To generate a system test skeleton, run the following command: ```bash $ bin/rails generate system_test users @@ -1405,7 +1404,7 @@ When you generate a new application or scaffold, an where all the configuration for your system tests should live. If you want to change the default settings, you can change what the system tests -are "driven by". If you want to change the driver from Selenium to Cuprite, you'd add the `cuprite` gem to your `Gemfile`. Then in your +are "driven by". If you want to change the driver from Selenium to Cuprite, you'd add the [`cuprite`](https://github.com/rubycdp/cuprite) gem to your `Gemfile`. Then in your `application_system_test_case.rb` file you'd do the following: ```ruby @@ -1497,9 +1496,8 @@ settings. ### Implementing a System Test -Next a system test will be added to the blog application. This example will demonstrate how to -write a system test by visiting the index page and creating a new blog -article. +This section will demonstrate how to +add a system test to your application, which tests a visit to the index page to create a new blog article. If you used the scaffold generator, a system test skeleton was automatically created for you. If you didn't use the scaffold generator, start by creating a @@ -1544,7 +1542,7 @@ sure to run `bin/rails test:system` to actually run them. You can also run #### Creating Articles System Test -Now let's test the flow for creating a new article in our blog. +Now you can test the flow for creating a new article. ```ruby test "should create Article" do @@ -1571,8 +1569,7 @@ Then the test will fill in the title and body of the article with the specified text. Once the fields are filled in, "Create Article" is clicked on which will send a POST request to `/articles/create`. -We will be redirected back to the articles index page and there we assert that -the text from the new article's title is on the articles index page. +This redirects the user back to the articles index page, and there it is asserted that the text from the new article's title is on the articles index page. #### Testing for Multiple Screen Sizes @@ -1638,7 +1635,7 @@ take a screenshot of the browser. #### Taking It Further -The beauty of system testing is that it is similar to [integration +System testing is similar to [integration testing](#integration-testing) in that it tests the user's interaction with your controller, model, and view, but system testing tests your application as if a real user were using it. With system tests, you @@ -1681,7 +1678,7 @@ end #### 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 +into separate files. A good place to store them is `test/lib` or `test/test_helpers`. ```ruby @@ -1693,7 +1690,7 @@ module MultipleAssertions end ``` -These helpers can then be explicitly required as needed and included as needed +These helpers can then be explicitly required and included as needed: ```ruby require "test_helper" @@ -1708,7 +1705,7 @@ class NumberTest < ActiveSupport::TestCase end ``` -or they can continue to be included directly into the relevant parent classes +They can also continue to be included directly into the relevant parent classes: ```ruby # test/test_helper.rb @@ -1737,7 +1734,7 @@ Testing Routes -------------- Like everything else in your Rails application, you can test your routes. Route -tests reside in `test/controllers/` or are part of controller tests. If your application has complex routes, Rails provides a number of useful +tests are stored in `test/controllers/` or are part of controller tests. If your application has complex routes, Rails provides a number of useful helpers to test them. For more information on routing assertions available in Rails, see the API @@ -1749,8 +1746,10 @@ Testing Views Testing the response to your request by asserting the presence of key HTML elements and their content is one way to test the views of your application. -Like route tests, view tests reside in `test/controllers/` or are part of -controller tests. +Like route tests, view tests are stored in `test/controllers/` or are part of +controller tests. + +### Querying the HTML Methods like `assert_dom` and `assert_dom_equal` allow you to query HTML elements of the response by using a simple yet powerful syntax. @@ -1820,8 +1819,7 @@ end If your application depends on [Nokogiri >= 1.14.0](https://github.com/sparklemotion/nokogiri/releases/tag/v1.14.0) or -higher, and [minitest >= ->5.18.0](https://github.com/minitest/minitest/blob/v5.18.0/History.rdoc#5180--2023-03-04-), +higher, and [minitest >= 5.18.0](https://github.com/minitest/minitest/blob/v5.18.0/History.rdoc#5180--2023-03-04-), `document_root_element` supports [Ruby's Pattern Matching](https://docs.ruby-lang.org/en/master/syntax/pattern_matching_rdoc.html): @@ -1876,6 +1874,8 @@ end More information about the assertions included by Capybara can be found in the [Capybara Assertions](#capybara-assertions) section. +### Parsing View Content + Starting in Action View version 7.1, the `#rendered` helper method returns an object capable of parsing the view partial's rendered content. From e855f4d835d5adf6afc868972fd732c7eef805d5 Mon Sep 17 00:00:00 2001 From: harriet oughton Date: Sat, 7 Dec 2024 17:47:12 +0000 Subject: [PATCH 25/31] Add final proof-read changes before review --- guides/source/testing.md | 49 ++++++++++++---------------------------- 1 file changed, 14 insertions(+), 35 deletions(-) diff --git a/guides/source/testing.md b/guides/source/testing.md index 850e91ce974d4..631f59984735d 100644 --- a/guides/source/testing.md +++ b/guides/source/testing.md @@ -1876,13 +1876,13 @@ More information about the assertions included by Capybara can be found in the [ ### Parsing View Content -Starting in Action View version 7.1, the `#rendered` helper method returns an +Starting in Action View version 7.1, the `rendered` helper method returns an object capable of parsing the view partial's rendered content. -To transform the `String` content returned by the `#rendered` method into an -object, define a parser by calling `.register_parser`. Calling `.register_parser -:rss` defines a `#rendered.rss` helper method. For example, to parse rendered -[RSS content][] into an object with `#rendered.rss`, register a call to +To transform the `String` content returned by the `rendered` method into an +object, define a parser by calling [`register_parser`](https://apidock.com/rails/v7.1.3.4/ActionView/TestCase/Behavior/ClassMethods/register_parser). Calling `register_parser +:rss` defines a `rendered.rss` helper method. For example, to parse rendered +[RSS content][] into an object with `rendered.rss`, register a call to `RSS::Parser.parse`: ```ruby @@ -1947,8 +1947,8 @@ end [Partial](layouts_and_rendering.html#using-partials) templates - usually called "partials" - can break the rendering process into more -manageable chunks. With partials, you can extract pieces of code from your -templates to separate files and reuse them throughout your templates. +manageable chunks. With partials, you can extract sections of code from your +views to separate files and reuse them in multiple places. View tests provide an opportunity to test that partials render content the way you expect. View partial tests can be stored in `test/views/` and inherit from @@ -1986,7 +1986,7 @@ end ### Testing View Helpers -A helper is just a simple module where you can define methods which are +A helper is a module where you can define methods which are available in your views. In order to test helpers, all you need to do is check that the output of the @@ -2036,9 +2036,7 @@ 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](#fixtures)). In the functional tests you don't so much test the -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. +details produced by the mailer; instead, you test that the 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 @@ -2062,9 +2060,7 @@ above. #### The Basic Test Case -Here's a unit test to test a mailer named `UserMailer` whose action `invite` is -used to send an invitation to a friend. It is an adapted version of the base -test created by the generator for an `invite` action. +Here's a unit test to test a mailer named `UserMailer` whose action `invite` is used to send an invitation to a friend: ```ruby require "test_helper" @@ -2089,10 +2085,9 @@ class UserMailerTest < ActionMailer::TestCase end ``` -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. +In the test the email is created and the returned object is stored in the `email` +variable. The first assert checks it was sent, then, in the +second batch of assertions, the email contents are checked. The helper `read_fixture` is used to read in the content from this file. NOTE: `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 @@ -2524,9 +2519,7 @@ which runs all tests including system tests. Parallel Testing ---------------- -Running tests in parallel reduces the time it takes your entire test suite to run. While forking -processes is the default method, threading is supported as well. Running tests -in parallel reduces the time it takes your entire test suite to run. +Running tests in parallel reduces the time it takes your entire test suite to run. While forking processes is the default method, threading is supported as well. ### Parallel Testing with Processes @@ -2679,8 +2672,6 @@ default. If your project does not have continuous integration, you can still eager load in the test suite by calling `Rails.application.eager_load!`: -#### Minitest - ```ruby require "test_helper" @@ -2691,18 +2682,6 @@ class ZeitwerkComplianceTest < ActiveSupport::TestCase end ``` -#### RSpec - -```ruby -require "rails_helper" - -RSpec.describe "Zeitwerk compliance" do - it "eager loads all files without errors" do - expect { Rails.application.eager_load! }.not_to raise_error - end -end -``` - Additional Testing Resources ---------------------------- From a36c39a436fcd8ce7589d3cf3ef4a599e352b2ed Mon Sep 17 00:00:00 2001 From: harriet oughton Date: Sat, 7 Dec 2024 18:28:18 +0000 Subject: [PATCH 26/31] Wrap text with 80 columns --- guides/source/testing.md | 413 +++++++++++++++++++++++---------------- 1 file changed, 246 insertions(+), 167 deletions(-) diff --git a/guides/source/testing.md b/guides/source/testing.md index 631f59984735d..49b65659d787f 100644 --- a/guides/source/testing.md +++ b/guides/source/testing.md @@ -17,15 +17,20 @@ After reading this guide, you will know: Why Write Tests? ---------------- -Writing automated tests can be a faster way of ensuring your code continues to work as expected than manual testing through the browser or the console. Failing tests can quickly reveal issues, allowing you to identify and fix bugs early in the development process. This practice not only improves the reliability of your code but also improves confidence in your changes. +Writing automated tests can be a faster way of ensuring your code continues to +work as expected than manual testing through the browser or the console. Failing +tests can quickly reveal issues, allowing you to identify and fix bugs early in +the development process. This practice not only improves the reliability of your +code but also improves confidence in your changes. -Rails makes it easy to write tests. You can read more about Rails' built in support for testing in the next section. +Rails makes it easy to write tests. You can read more about Rails' built in +support for testing in the next section. Introduction to Testing ----------------------- -With Rails, testing is central -to the development process right from the creation of a new application. +With Rails, testing is central to the development process right from the +creation of a new application. ### Test Setup @@ -40,16 +45,28 @@ application_system_test_case.rb controllers/ helpers/ ### Test Directories -The `helpers`, `mailers`, and `models` directories store tests for [view helpers](#testing-view-helpers), [mailers](#testing-mailers), and [models](#testing-models), respectively. The `controllers` directory is used for [tests related to controllers](#functional-testing-for-controllers), routes, and views, where HTTP requests will be simulated and assertions made on the outcomes. The `integration` directory is reserved for [tests that cover interactions between controllers](#integration-testing). - -The `system` test directory holds [system tests](#system-testing), 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](https://github.com/teamcapybara/capybara) and perform in-browser tests for your application. - -[Fixtures](https://api.rubyonrails.org/v3.1/classes/ActiveRecord/Fixtures.html) are a way of mocking up data to use in your tests, so that you don't have to use 'real' data. They are stored in the `fixtures` directory, and you can read more about them in the [Fixtures](#fixtures) section below. - -A `jobs` directory will also be created for your job tests when you first [generate a job](active_job_basics.html#create-the-job). +The `helpers`, `mailers`, and `models` directories store tests for [view +helpers](#testing-view-helpers), [mailers](#testing-mailers), and +[models](#testing-models), respectively. The `controllers` directory is used for +[tests related to controllers](#functional-testing-for-controllers), routes, and +views, where HTTP requests will be simulated and assertions made on the +outcomes. The `integration` directory is reserved for [tests that cover +interactions between controllers](#integration-testing). + +The `system` test directory holds [system tests](#system-testing), 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](https://github.com/teamcapybara/capybara) and perform in-browser +tests for your application. + +[Fixtures](https://api.rubyonrails.org/v3.1/classes/ActiveRecord/Fixtures.html) +are a way of mocking up data to use in your tests, so that you don't have to use +'real' data. They are stored in the `fixtures` directory, and you can read more +about them in the [Fixtures](#fixtures) section below. + +A `jobs` directory will also be created for your job tests when you first +[generate a job](active_job_basics.html#create-the-job). The `test_helper.rb` file holds the default configuration for your tests. @@ -101,7 +118,9 @@ testing code and terminology. require "test_helper" ``` -Requiring the file, `test_helper.rb`, loads the default configuration to run tests. All methods added to this file are also available in tests when this file is included. +Requiring the file, `test_helper.rb`, loads the default configuration to run +tests. All methods added to this file are also available in tests when this file +is included. ```ruby class ArticleTest < ActiveSupport::TestCase @@ -111,8 +130,8 @@ end This is called a test case, because the `ArticleTest` class inherits from `ActiveSupport::TestCase`. It therefore also has all the methods from -`ActiveSupport::TestCase` available to it. [Later in this guide](#assertions-in-test-cases), we'll see some -of the methods this gives us. +`ActiveSupport::TestCase` available to it. [Later in this +guide](#assertions-in-test-cases), we'll see some of the methods this 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 @@ -120,7 +139,9 @@ called a test. So, methods defined as `test_password` and `test_valid_password` are 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 standard `Minitest::Unit` test with method names prefixed with `test_`, allowing you to focus on writing the test logic without having to think about naming the methods. For example, you can write: +a standard `Minitest::Unit` test with method names prefixed with `test_`, +allowing you to focus on writing the test logic without having to think about +naming the methods. For example, you can write: ```ruby test "the truth" do @@ -140,9 +161,9 @@ Although you can still use regular method definitions, using the `test` macro allows for a more readable test name. NOTE: The method name is generated by replacing spaces with underscores. The -result does not need to be a valid Ruby identifier, as Ruby allows any string to serve -as a method name, including those containing punctuation characters. While this -may require using `define_method` and `send` to define and invoke such +result does not need to be a valid Ruby identifier, as Ruby allows any string to +serve as a method name, including those containing punctuation characters. While +this may require using `define_method` and `send` to define and invoke such methods, there are few formal restrictions on the names themselves. This part of a test is called an 'assertion': @@ -166,8 +187,8 @@ the test pass. #### 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. In this example, it is asserted that the article will -not save without meeting certain criteria; hence, if the article saves +`article_test.rb` test case. In this example, it is asserted that the article +will not save without meeting certain criteria; hence, if the article saves successfully, the test will fail, demonstrating a test failure. ```ruby @@ -177,8 +198,8 @@ test "should not save article without title" do end ``` -Here is the output if this newly added test is run (with `6` being the line number where the test is -defined): +Here is the output if this newly added test is run (with `6` being the line +number where the test is defined): ```bash $ bin/rails test test/models/article_test.rb:6 @@ -203,11 +224,12 @@ 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` indicates a test failure. The section under `Failure` includes the name of the failing test, -followed by a stack trace and a message showing the actual value and the expected value from the -assertion. The default assertion messages offer just enough information to help identify the error. -For improved readability, every assertion allows an optional message parameter to customize the failure -message, as shown below: +In the output, `F` indicates a test failure. The section under `Failure` +includes the name of the failing test, followed by a stack trace and a message +showing the actual value and the expected value from the assertion. The default +assertion messages offer just enough information to help identify the error. For +improved readability, every assertion allows an optional message parameter to +customize the failure message, as shown below: ```ruby test "should not save article without title" do @@ -233,8 +255,9 @@ class Article < ApplicationRecord end ``` -Now the test should pass, as the article in our test -has not been initialized with a `title`, so the model validation will prevent the save. This can be verified by running the test again: +Now the test should pass, as the article in our test has not been initialized +with a `title`, so the model validation will prevent the save. This can be +verified by running the test again: ```bash $ bin/rails test test/models/article_test.rb:6 @@ -252,7 +275,10 @@ Finished in 0.027476s, 36.3952 runs/s, 36.3952 assertions/s. The small green dot displayed means that the test has passed successfully. -NOTE: In that process, a test was written first which fails for a desired functionality, then after, some code was written which adds the functionality. Finally, the test was run again to ensure it passes. This approach to software development is referred to as _Test-Driven Development_ (TDD). +NOTE: In that process, a test was written first which fails for a desired +functionality, then after, some code was written which adds the functionality. +Finally, the test was run again to ensure it passes. This approach to software +development is referred to as _Test-Driven Development_ (TDD). #### Reporting Errors @@ -292,8 +318,8 @@ 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 an error. The green dot above -the 'Finished' line denotes the one passing test. +Notice the 'E' in the output. It denotes a test with an error. The green dot +above the 'Finished' line denotes the one passing test. 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 @@ -301,18 +327,18 @@ 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 the backtrace and will only print lines relevant to your -application. This eliminates noise and helps you to focus on your -code. However, in situations when you want to see the full backtrace, set -the `-b` (or `--backtrace`) argument to enable this behavior: +When a test fails you are presented with the corresponding backtrace. By +default, Rails filters the backtrace and will only print lines relevant to your +application. This eliminates noise and helps you to focus on your code. However, +in situations when you want to see the full backtrace, set the `-b` (or +`--backtrace`) argument to enable this behavior: ```bash $ bin/rails test -b test/models/article_test.rb ``` -If you want this test to pass you can modify it to use `assert_raises` (so you are -now checking for the presence of the error) like so: +If you want this test to pass you can modify it to use `assert_raises` (so you +are now checking for the presence of the error) like so: ```ruby test "should report error" do @@ -375,13 +401,13 @@ specify to make your test failure messages clearer. | `assert_no_error_reported { block }` | Ensures that no errors have been reported, e.g. `assert_no_error_reported { perform_service }`| | `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 and -more up-to-date list, please check the [minitest API +The above are a subset of assertions that minitest supports. For an exhaustive +and more up-to-date list, please check the [minitest API documentation](http://docs.seattlerb.org/minitest/Minitest), specifically [`Minitest::Assertions`](http://docs.seattlerb.org/minitest/Minitest/Assertions.html). -With minitest you can add your own assertions. In fact, that's exactly what Rails does. It includes some -specialized assertions to make your life easier. +With minitest you can add 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 a topic that we won't cover in depth in this guide. @@ -457,14 +483,14 @@ 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 your tests. -NOTE: For more information on `minitest`, refer to the -[minitest documentation](http://docs.seattlerb.org/minitest). +NOTE: For more information on `minitest`, refer to the [minitest +documentation](http://docs.seattlerb.org/minitest). ### Transactions By default, Rails automatically wraps tests in a database transaction that is -rolled back once completed. This makes tests independent of each other and -means that changes to the database are only visible within a single test. +rolled back once completed. This makes tests independent of each other and means +that changes to the database are only visible within a single test. ```ruby class MyTest < ActiveSupport::TestCase @@ -476,8 +502,9 @@ class MyTest < ActiveSupport::TestCase end ``` -The method [`ActiveRecord::Base.current_transaction`](https://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html#method-i-current_transaction) still acts as intended, -though: +The method +[`ActiveRecord::Base.current_transaction`](https://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html#method-i-current_transaction) +still acts as intended, though: ```ruby class MyTest < ActiveSupport::TestCase @@ -508,7 +535,8 @@ end 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 appending the filename to the `bin/rails test` command. +Or we can run a single test file by appending the filename to the `bin/rails +test` command. ```bash $ bin/rails test test/models/article_test.rb @@ -562,9 +590,9 @@ 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, -showing verbose progress, and so on. Check the -documentation of the test runner using the command below: +The test runner also provides a lot of other features like failing fast, showing +verbose progress, and so on. Check the documentation of the test runner using +the command below: ```bash $ bin/rails test -h @@ -612,10 +640,13 @@ Known extensions: rails, pride The Test Database ----------------- -Just about every Rails application interacts heavily with a database and so your tests will need a database to interact with as well. This section covers how to set up this test database and populate it with sample data. +Just about every Rails application interacts heavily with a database and so your +tests will need a database to interact with as well. This section covers how to +set up this test database and populate it with sample data. -As mentioned in the [Test Envionment section](#the-test-environment), every Rails application has three environments: development, test, and production. The database for each one of them is configured in -`config/database.yml`. +As mentioned in the [Test Envionment section](#the-test-environment), every +Rails application has three environments: development, test, and production. The +database for each one of them is configured in `config/database.yml`. A dedicated test database allows you to set up and interact with test data in isolation. This way your tests can interact with test data with confidence, @@ -623,13 +654,12 @@ without worrying about the data in the development or production databases. ### Maintaining the Test Database Schema -In order to run your tests, your test database needs the current -schema. The test helper checks whether your test database has any pending -migrations. 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 (using `bin/rails db:migrate RAILS_ENV=test`) will bring -the schema up to date. +In order to run your tests, your test database needs the current schema. The +test helper checks whether your test database has any pending migrations. 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 (using +`bin/rails db:migrate RAILS_ENV=test`) will bring the schema up to date. NOTE: If there were modifications to existing migrations, the test database needs to be rebuilt. This can be done by executing `bin/rails test:db`. @@ -783,10 +813,11 @@ default. Loading involves three steps: 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 permission errors on running tests, make sure the database -user has the permission to disable these triggers in the testing environment. -(In PostgreSQL, only superusers can disable all triggers. Read more about -[permissions in the PostgreSQL docs](https://www.postgresql.org/docs/current/sql-altertable.html)). +are getting permission errors on running tests, make sure the database user has +the permission to disable these triggers in the testing environment. (In +PostgreSQL, only superusers can disable all triggers. Read more about +[permissions in the PostgreSQL +docs](https://www.postgresql.org/docs/current/sql-altertable.html)). #### Fixtures are Active Record Objects @@ -818,9 +849,9 @@ users(:david, :steve) Testing Models -------------- -Model tests are used to test the models of your application and their -associated logic. You can test this logic using the assertions and fixtures that -we've explored in the sections above. +Model tests are used to test the models of your application and their associated +logic. You can test this logic using the assertions and fixtures that we've +explored in the sections above. Rails model tests are stored under the `test/models` directory. Rails provides a generator to create a model test skeleton for you. @@ -850,9 +881,10 @@ Instead, they inherit from Functional Testing for Controllers ---------------------------------- -When writing functional tests, you are focusing on testing how controller actions handle the requests and the expected result or response. Functional controller -tests are sometimes used in cases where system tests are not appropriate, e.g., -to confirm an API response. +When writing functional tests, you are focusing on testing how controller +actions handle the requests and the expected result or response. Functional +controller tests are sometimes used in cases where system tests are not +appropriate, e.g., to confirm an API response. ### What to Include in Your Functional Tests @@ -929,29 +961,31 @@ The `get` method kicks off the web request and populates the results into the All of these keyword arguments are optional. -Example: Calling the `:show` action (via a `get` request) for the first `Article`, passing in an -`HTTP_REFERER` header: +Example: Calling the `:show` action (via a `get` request) for the first +`Article`, passing in an `HTTP_REFERER` header: ```ruby get article_url(Article.first), headers: { "HTTP_REFERER" => "http://example.com/home" } ``` -Another example: Calling the `:update` action (via a `patch` request) for the last `Article`, passing in -new text for the `title` in `params`, as an AJAX request: +Another example: Calling the `:update` action (via a `patch` request) for the +last `Article`, passing in new text for the `title` in `params`, as an AJAX +request: ```ruby patch article_url(Article.last), params: { article: { title: "updated" } }, xhr: true ``` -One more example: Calling the `:create` action (via a `post` request) to create a new article, passing -in text for the `title` in `params`, as JSON request: +One more example: Calling the `:create` action (via a `post` request) to create +a new article, passing in text for the `title` in `params`, as JSON request: ```ruby post articles_url, params: { article: { title: "Ahoy!" } }, as: :json ``` NOTE: If you try running the `test_should_create_article` test from -`articles_controller_test.rb` it will (correctly) fail due to the newly added model-level validation. +`articles_controller_test.rb` it will (correctly) fail due to the newly added +model-level validation. Now to modify the `test_should_create_article` test in `articles_controller_test.rb` so that this test passes: @@ -989,16 +1023,21 @@ request. There are 6 request types supported in Rails functional tests: * `delete` All of the request types have equivalent methods that you can use. In a typical -C.R.U.D. application you'll be using `post`, `get`, `put`, and `delete` most often. +C.R.U.D. application you'll be using `post`, `get`, `put`, and `delete` most +often. NOTE: Functional tests do not verify whether the specified request type is -accepted by the action; instead, they focus on the result. For testing the request type, request tests are available, making your tests more purposeful. +accepted by the action; instead, they focus on the result. For testing the +request type, request tests are available, making your tests more purposeful. ### Testing XHR (AJAX) Requests -An AJAX request (Asynchronous Javscript and XML) is a technique where content is fetched from the server using asynchronous HTTP requests and the relevant parts of the page are updated without requiring a full page load. +An AJAX request (Asynchronous Javscript and XML) is a technique where content is +fetched from the server using asynchronous HTTP requests and the relevant parts +of the page are updated without requiring a full page load. -To test AJAX requests, you can specify the `xhr: true` option to `get`, `post`, `patch`, `put`, and `delete` methods. For example: +To test AJAX requests, you can specify the `xhr: true` option to `get`, `post`, +`patch`, `put`, and `delete` methods. For example: ```ruby test "AJAX request" do @@ -1068,7 +1107,11 @@ get articles_url, headers: { "HTTP_REFERER": "http://example.com/home" } # simul ### Testing `flash` Notices -As can be seen in the [testing other request objects section](#testing-other-request-objects), one of the three hash objects that is accessible in the tests is `flash`. This section outlines how to test the appearance of a `flash` message in our blog application whenever someone successfully creates a new article. +As can be seen in the [testing other request objects +section](#testing-other-request-objects), one of the three hash objects that is +accessible in the tests is `flash`. This section outlines how to test the +appearance of a `flash` message in our blog application whenever someone +successfully creates a new article. First, an assertion should be added to the `test_should_create_article` test: @@ -1107,8 +1150,8 @@ ArticlesControllerTest#test_should_create_article [/test/controllers/articles_co 1 runs, 4 assertions, 1 failures, 0 errors, 0 skips ``` -Now implement the flash message in the controller. The `:create` action -should look like this: +Now implement the flash message in the controller. The `:create` action should +look like this: ```ruby def create @@ -1144,8 +1187,8 @@ message will already be implemented in your `create` action. ### Tests for `show`, `update`, and `delete` Actions -So far in the guide tests for the `:index` as well as the`:create` -action have been outlined. What about the other actions? +So far in the guide tests for the `:index` as well as the`:create` action have +been outlined. What about the other actions? You can write a test for `:show` as follows: @@ -1157,7 +1200,8 @@ test "should show article" do end ``` -If you remember from our discussion earlier on [fixtures](#fixtures), the `articles()` method will provide access to the articles fixtures. +If you remember from our discussion earlier on [fixtures](#fixtures), the +`articles()` method will provide access to the articles fixtures. How about deleting an existing article? @@ -1187,10 +1231,10 @@ test "should update article" do end ``` -Notice that there is some duplication in these three tests - they both -access the same article fixture data. It is possible to D.R.Y. ('Don't -Repeat Yourself') the implementation by using the `setup` and `teardown` methods provided by -`ActiveSupport::Callbacks`. +Notice that there is some duplication in these three tests - they both access +the same article fixture data. It is possible to D.R.Y. ('Don't Repeat +Yourself') the implementation by using the `setup` and `teardown` methods +provided by `ActiveSupport::Callbacks`. The tests might look like this: @@ -1240,9 +1284,10 @@ can also accept a block, lambda, or a method name as a symbol to be called. Integration Testing ------------------- -Integration tests take functional controller tests one step further - they focus on testing how several parts of an application interact, and are -generally used to test important workflows. Rails -integration tests are stored in the `test/integration` directory. +Integration tests take functional controller tests one step further - they focus +on testing how several parts of an application interact, and are generally used +to test important workflows. Rails integration tests are stored in the +`test/integration` directory. Rails provides a generator to create an integration test skeleton as follows: @@ -1264,9 +1309,11 @@ class UserFlowsTest < ActionDispatch::IntegrationTest end ``` -Here the test is inheriting from [`ActionDispatch::IntegrationTest`](https://api.rubyonrails.org/classes/ActionDispatch/IntegrationTest.html). This makes -some additional [helpers available for integration tests](testing.html#helpers-available-for-integration-tests) alongside the standard testing -helpers. +Here the test is inheriting from +[`ActionDispatch::IntegrationTest`](https://api.rubyonrails.org/classes/ActionDispatch/IntegrationTest.html). +This makes some additional [helpers available for integration +tests](testing.html#helpers-available-for-integration-tests) alongside the +standard testing helpers. ### Implementing an Integration Test @@ -1280,8 +1327,8 @@ Start by generating the integration test skeleton: $ bin/rails generate integration_test blog_flow ``` -It should have created a test file placeholder. With the output of the -previous command you should see: +It should have created a test file placeholder. With the output of the previous +command you should see: ``` invoke test_unit @@ -1301,9 +1348,13 @@ class BlogFlowTest < ActionDispatch::IntegrationTest end ``` -If you visit the root path, you should see `welcome/index.html.erb` rendered for the view. So this assertion should pass. +If you visit the root path, you should see `welcome/index.html.erb` rendered for +the view. So this assertion should pass. -NOTE: The assertion `assert_selector` is available in integration tests to check the presence of key HTML elements and their content. It is similar to `assert_dom`, which should be used when [testing views](#testing-views) as outlined in the section below. +NOTE: The assertion `assert_selector` is available in integration tests to check +the presence of key HTML elements and their content. It is similar to +`assert_dom`, which should be used when [testing views](#testing-views) as +outlined in the section below. #### Creating Articles Integration @@ -1324,9 +1375,11 @@ test "can create an article" do end ``` -The `:new` action of our Articles controller is called first, and the response should be successful. +The `:new` action of our Articles controller is called first, and the response +should be successful. -Next, a `post` request is made to the `:create` action of the Articles controller: +Next, a `post` request is made to the `:create` action of the Articles +controller: ```ruby post "/articles", @@ -1335,28 +1388,38 @@ assert_response :redirect follow_redirect! ``` -The two lines following the request are to handle the redirect setup when creating a new article. +The two lines following the request are to handle the redirect 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. -Finally it can be asserted that the response was successful and the newly-created article is readable on the page. +Finally it can be asserted that the response was successful and the +newly-created article is readable on the page. -A very small workflow for visiting our blog -and creating a new article was successfully tested above. To extend this, additional tests could be added for features like adding comments, editing comments or removing articles. Integration tests -are a great place to experiment with all kinds of use cases for our applications. +A very small workflow for visiting our blog and creating a new article was +successfully tested above. To extend this, additional tests could be added for +features like adding comments, editing comments or removing articles. +Integration tests are a great place to experiment with all kinds of use cases +for our applications. ### Helpers Available for Integration Tests -There are numerous helpers to choose from for use in integration tests. Some include: +There are numerous helpers to choose from for use in integration tests. Some +include: -* [`ActionDispatch::Integration::Runner`](https://api.rubyonrails.org/classes/ActionDispatch/Integration/Runner.html) for helpers relating to the integration test runner, including creating a new session. +* [`ActionDispatch::Integration::Runner`](https://api.rubyonrails.org/classes/ActionDispatch/Integration/Runner.html) + for helpers relating to the integration test runner, including creating a new + session. -* [`ActionDispatch::Integration::RequestHelpers`](https://api.rubyonrails.org/classes/ActionDispatch/Integration/RequestHelpers.html) for performing requests. +* [`ActionDispatch::Integration::RequestHelpers`](https://api.rubyonrails.org/classes/ActionDispatch/Integration/RequestHelpers.html) + for performing requests. -* [`ActionDispatch::TestProcess::FixtureFile`](https://api.rubyonrails.org/classes/ActionDispatch/TestProcess/FixtureFile.html) for uploading files. +* [`ActionDispatch::TestProcess::FixtureFile`](https://api.rubyonrails.org/classes/ActionDispatch/TestProcess/FixtureFile.html) + for uploading files. -* [`ActionDispatch::Integration::Session`](https://api.rubyonrails.org/classes/ActionDispatch/Integration/Session.html) to modify sessions or the state of the integration tests. +* [`ActionDispatch::Integration::Session`](https://api.rubyonrails.org/classes/ActionDispatch/Integration/Session.html) + to modify sessions or the state of the integration tests. System Testing -------------- @@ -1404,8 +1467,10 @@ When you generate a new application or scaffold, an where all the configuration for your system tests should live. If you want to change the default settings, you can change what the system tests -are "driven by". If you want to change the driver from Selenium to Cuprite, you'd add the [`cuprite`](https://github.com/rubycdp/cuprite) gem to your `Gemfile`. Then in your -`application_system_test_case.rb` file you'd do the following: +are "driven by". If you want to change the driver from Selenium to Cuprite, +you'd add the [`cuprite`](https://github.com/rubycdp/cuprite) gem to your +`Gemfile`. Then in your `application_system_test_case.rb` file you'd do the +following: ```ruby require "test_helper" @@ -1466,8 +1531,8 @@ Now you should get a connection to the remote browser. $ SELENIUM_REMOTE_URL=http://localhost:4444/wd/hub bin/rails test:system ``` -If your application is remote, e.g. within a Docker -container, Capybara needs more input about how to [call remote +If your application is remote, e.g. within a Docker container, Capybara needs +more input about how to [call remote servers](https://github.com/teamcapybara/capybara#calling-remote-servers). ```ruby @@ -1487,8 +1552,8 @@ Now you should get a connection to a remote browser and server, regardless if it is running in a Docker container or CI. If your Capybara configuration requires more setup than provided by Rails, this -additional configuration can be added into the -`application_system_test_case.rb` file. +additional configuration can be added into the `application_system_test_case.rb` +file. Please see [Capybara's documentation](https://github.com/teamcapybara/capybara#setup) for additional @@ -1496,8 +1561,8 @@ settings. ### Implementing a System Test -This section will demonstrate how to -add a system test to your application, which tests a visit to the index page to create a new blog article. +This section will demonstrate how to add a system test to your application, +which tests a visit to the index page to create a new blog article. If you used the scaffold generator, a system test skeleton was automatically created for you. If you didn't use the scaffold generator, start by creating a @@ -1507,8 +1572,8 @@ system test skeleton. $ bin/rails generate system_test articles ``` -It should have created a test file placeholder. With the output of the -previous command you should see: +It should have created a test file placeholder. With the output of the previous +command you should see: ``` invoke test_unit @@ -1569,7 +1634,9 @@ Then the test will fill in the title and body of the article with the specified text. Once the fields are filled in, "Create Article" is clicked on which will send a POST request to `/articles/create`. -This redirects the user back to the articles index page, and there it is asserted that the text from the new article's title is on the articles index page. +This redirects the user back to the articles index page, and there it is +asserted that the text from the new article's title is on the articles index +page. #### Testing for Multiple Screen Sizes @@ -1605,7 +1672,8 @@ end #### Capybara Assertions Here's an extract of the assertions provided by -[`Capybara`](https://rubydoc.info/github/teamcapybara/capybara/master/Capybara/Minitest/Assertions) which can be used in system tests. +[`Capybara`](https://rubydoc.info/github/teamcapybara/capybara/master/Capybara/Minitest/Assertions) +which can be used in system tests. | Assertion | Purpose | | ---------------------------------------------------------------- | ------- | @@ -1635,17 +1703,17 @@ take a screenshot of the browser. #### Taking It Further -System testing is similar to [integration -testing](#integration-testing) in that it tests the user's interaction with your -controller, model, and view, but system testing -tests your application as if a real user were using it. With system tests, you -can test anything that a user would do in your application such as -commenting, deleting articles, publishing draft articles, etc. +System testing is similar to [integration testing](#integration-testing) in that +it tests the user's interaction with your controller, model, and view, but +system testing tests your application as if a real user were using it. With +system tests, you can test anything that a user would do in your application +such as commenting, deleting articles, publishing draft articles, etc. Test Helpers ------------ -To avoid code duplication, you can add your own test helpers. Here is an example for signing in: +To avoid code duplication, you can add your own test helpers. Here is an example +for signing in: ```ruby # test/test_helper.rb @@ -1734,8 +1802,9 @@ Testing Routes -------------- Like everything else in your Rails application, you can test your routes. Route -tests are stored in `test/controllers/` or are part of controller tests. If your application has complex routes, Rails provides a number of useful -helpers to test them. +tests are stored in `test/controllers/` or are part of controller tests. If your +application has complex routes, Rails provides a number of useful helpers to +test them. For more information on routing assertions available in Rails, see the API documentation for @@ -1790,15 +1859,16 @@ assert_dom "ol" do end ``` -The `assert_dom_equal` method compares two HTML strings to see if they are equal: +The `assert_dom_equal` method compares two HTML strings to see if they are +equal: ```ruby assert_dom_equal 'Read more', link_to("Read more", "http://www.further-reading.com") ``` -For more advanced usage, refer to the -[`rails-dom-testing` documentation](https://github.com/rails/rails-dom-testing). +For more advanced usage, refer to the [`rails-dom-testing` +documentation](https://github.com/rails/rails-dom-testing). In order to integrate with [rails-dom-testing][], tests that inherit from `ActionView::TestCase` declare a `document_root_element` method that returns the @@ -1819,7 +1889,8 @@ end If your application depends on [Nokogiri >= 1.14.0](https://github.com/sparklemotion/nokogiri/releases/tag/v1.14.0) or -higher, and [minitest >= 5.18.0](https://github.com/minitest/minitest/blob/v5.18.0/History.rdoc#5180--2023-03-04-), +higher, and [minitest >= +5.18.0](https://github.com/minitest/minitest/blob/v5.18.0/History.rdoc#5180--2023-03-04-), `document_root_element` supports [Ruby's Pattern Matching](https://docs.ruby-lang.org/en/master/syntax/pattern_matching_rdoc.html): @@ -1839,9 +1910,9 @@ end If you'd like to access the same [Capybara-powered Assertions](https://rubydoc.info/github/teamcapybara/capybara/master/Capybara/Minitest/Assertions) -that your [System Testing](#system-testing) tests -utilize, you can define a base class that inherits from `ActionView::TestCase` -and transforms the `document_root_element` into a `page` method: +that your [System Testing](#system-testing) tests utilize, you can define a base +class that inherits from `ActionView::TestCase` and transforms the +`document_root_element` into a `page` method: ```ruby # test/view_partial_test_case.rb @@ -1872,7 +1943,8 @@ class ArticlePartialTest < ViewPartialTestCase end ``` -More information about the assertions included by Capybara can be found in the [Capybara Assertions](#capybara-assertions) section. +More information about the assertions included by Capybara can be found in the +[Capybara Assertions](#capybara-assertions) section. ### Parsing View Content @@ -1880,10 +1952,11 @@ Starting in Action View version 7.1, the `rendered` helper method returns an object capable of parsing the view partial's rendered content. To transform the `String` content returned by the `rendered` method into an -object, define a parser by calling [`register_parser`](https://apidock.com/rails/v7.1.3.4/ActionView/TestCase/Behavior/ClassMethods/register_parser). Calling `register_parser -:rss` defines a `rendered.rss` helper method. For example, to parse rendered -[RSS content][] into an object with `rendered.rss`, register a call to -`RSS::Parser.parse`: +object, define a parser by calling +[`register_parser`](https://apidock.com/rails/v7.1.3.4/ActionView/TestCase/Behavior/ClassMethods/register_parser). +Calling `register_parser :rss` defines a `rendered.rss` helper method. For +example, to parse rendered [RSS content][] into an object with `rendered.rss`, +register a call to `RSS::Parser.parse`: ```ruby register_parser :rss, -> rendered { RSS::Parser.parse(rendered) } @@ -1946,9 +2019,9 @@ end ### Testing View Partials [Partial](layouts_and_rendering.html#using-partials) templates - usually called -"partials" - can break the rendering process into more -manageable chunks. With partials, you can extract sections of code from your -views to separate files and reuse them in multiple places. +"partials" - can break the rendering process into more manageable chunks. With +partials, you can extract sections of code from your views to separate files and +reuse them in multiple places. View tests provide an opportunity to test that partials render content the way you expect. View partial tests can be stored in `test/views/` and inherit from @@ -1986,8 +2059,8 @@ end ### Testing View Helpers -A helper is a module where you can define methods which are -available in your views. +A helper is a module where you can define methods which are available in your +views. 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 @@ -2036,7 +2109,9 @@ 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](#fixtures)). In the functional tests you don't so much test the -details produced by the mailer; instead, you test that the 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. +details produced by the mailer; instead, you test that the 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 @@ -2060,7 +2135,8 @@ above. #### 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: +Here's a unit test to test a mailer named `UserMailer` whose action `invite` is +used to send an invitation to a friend: ```ruby require "test_helper" @@ -2085,9 +2161,10 @@ class UserMailerTest < ActionMailer::TestCase end ``` -In the test the email is created and the returned object is stored in the `email` -variable. The first assert checks it was sent, then, in the -second batch of assertions, the email contents are checked. The helper `read_fixture` is used to read in the content from this file. +In the test the email is created and the returned object is stored in the +`email` variable. The first assert checks it was sent, then, in the second batch +of assertions, the email contents are checked. The helper `read_fixture` is used +to read in the content from this file. NOTE: `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 @@ -2519,14 +2596,16 @@ which runs all tests including system tests. Parallel Testing ---------------- -Running tests in parallel reduces the time it takes your entire test suite to run. While forking processes is the default method, threading is supported as well. +Running tests in parallel reduces the time it takes your entire test suite to +run. While forking processes is the default method, threading is supported as +well. ### Parallel Testing with Processes The default parallelization method is to fork processes using Ruby's DRb system. The processes are forked based on the number of workers provided. The default -number is the actual core count on the machine, but can be changed by -the number passed to the `parallelize` method. +number is the actual core count on the machine, but can be changed by the number +passed to the `parallelize` method. To enable parallelization add the following to your `test_helper.rb`: @@ -2599,8 +2678,8 @@ Rails applications generated from JRuby or TruffleRuby will automatically include the `with: :threads` option. NOTE: As in the section above, you can also use the environment variable -`PARALLEL_WORKERS` in this context, to change the number of workers -your test run should use. +`PARALLEL_WORKERS` in this context, to change the number of workers your test +run should use. ### Testing Parallel Transactions From 58fa1d2f7fdf7500e105a6972b47bf5474ec166b Mon Sep 17 00:00:00 2001 From: harriet oughton Date: Sat, 7 Dec 2024 19:23:13 +0000 Subject: [PATCH 27/31] Correct lint errors --- guides/source/testing.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/guides/source/testing.md b/guides/source/testing.md index 49b65659d787f..bb130bbb911c1 100644 --- a/guides/source/testing.md +++ b/guides/source/testing.md @@ -66,7 +66,7 @@ are a way of mocking up data to use in your tests, so that you don't have to use about them in the [Fixtures](#fixtures) section below. A `jobs` directory will also be created for your job tests when you first -[generate a job](active_job_basics.html#create-the-job). +[generate a job](active_job_basics.html#create-the-job). The `test_helper.rb` file holds the default configuration for your tests. @@ -1034,7 +1034,7 @@ request type, request tests are available, making your tests more purposeful. An AJAX request (Asynchronous Javscript and XML) is a technique where content is fetched from the server using asynchronous HTTP requests and the relevant parts -of the page are updated without requiring a full page load. +of the page are updated without requiring a full page load. To test AJAX requests, you can specify the `xhr: true` option to `get`, `post`, `patch`, `put`, and `delete` methods. For example: @@ -1093,7 +1093,7 @@ end HTTP headers are pieces of information sent along with HTTP requests to provide important metadata. CGI variables are environment variables used to exchange -information between the web server and the application. +information between the web server and the application. HTTP headers and CGI variables can be tested by being passed as headers: @@ -1287,7 +1287,7 @@ Integration Testing Integration tests take functional controller tests one step further - they focus on testing how several parts of an application interact, and are generally used to test important workflows. Rails integration tests are stored in the -`test/integration` directory. +`test/integration` directory. Rails provides a generator to create an integration test skeleton as follows: @@ -1743,7 +1743,7 @@ class ProfileControllerTest < ActionDispatch::IntegrationTest end ``` -#### Using Separate Files +### Using Separate Files If you find your helpers are cluttering `test_helper.rb`, you can extract them into separate files. A good place to store them is `test/lib` or @@ -1784,7 +1784,7 @@ class ActionDispatch::IntegrationTest end ``` -#### Eagerly Requiring Helpers +### 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 @@ -2256,7 +2256,7 @@ class UserMailerTest < ActionMailer::TestCase email = UserMailer.with(all: "good").create_invite("me@example.com", "friend@example.com") # Test that the email got enqueued with the correct mailer parameters and arguments - assert_enqueued_email_with UserMailer, :create_invite, + assert_enqueued_email_with UserMailer, :create_invite, params: { all: "good" }, args: ["me@example.com", "friend@example.com"] do email.deliver_later end From 156de71242c360b58869ccdc979e8e99e13fdc56 Mon Sep 17 00:00:00 2001 From: harriet oughton Date: Sat, 7 Dec 2024 19:41:34 +0000 Subject: [PATCH 28/31] Adjust mailer testing headings --- guides/source/testing.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/guides/source/testing.md b/guides/source/testing.md index fa04abf5b94fb..53ccaa9ea72e2 100644 --- a/guides/source/testing.md +++ b/guides/source/testing.md @@ -2103,8 +2103,6 @@ The goals of testing your mailer classes are to ensure that: * 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 From 1df2584cb78bcfb8e2243c3a542dee024c0b48ee Mon Sep 17 00:00:00 2001 From: harriet oughton Date: Sun, 8 Dec 2024 09:50:26 +0000 Subject: [PATCH 29/31] Fix Rubocop errors --- guides/source/testing.md | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/guides/source/testing.md b/guides/source/testing.md index 53ccaa9ea72e2..c09dff15f70cc 100644 --- a/guides/source/testing.md +++ b/guides/source/testing.md @@ -1539,11 +1539,10 @@ servers](https://github.com/teamcapybara/capybara#calling-remote-servers). require "test_helper" class ApplicationSystemTestCase < ActionDispatch::SystemTestCase - def setup do - Capybara.server_host = "0.0.0.0" # bind to all interfaces - Capybara.app_host = "http://#{IPSocket.getaddress(Socket.gethostname)}" if ENV["SELENIUM_REMOTE_URL"].present? + setup do + Capybara.server_host = "0.0.0.0" # bind to all interfaces + Capybara.app_host = "http://#{IPSocket.getaddress(Socket.gethostname)}" if ENV["SELENIUM_REMOTE_URL"].present? end - end # ... end ``` From 71f97675738aaab50e04d53baba952320c074d2d Mon Sep 17 00:00:00 2001 From: harriet oughton Date: Sun, 8 Dec 2024 10:06:25 +0000 Subject: [PATCH 30/31] Update guide description --- guides/source/documents.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/guides/source/documents.yaml b/guides/source/documents.yaml index 140dbe7d570b7..ab6c77230f019 100644 --- a/guides/source/documents.yaml +++ b/guides/source/documents.yaml @@ -170,7 +170,7 @@ - name: Testing Rails Applications url: testing.html - description: This is a rather comprehensive guide to the various testing facilities in Rails. It covers everything from 'What is a test?' to Integration Testing. Enjoy. + description: This guide explores how to write tests in Rails. It also covers test configuration and compares approaches to testing an application. - name: Securing Rails Applications url: security.html From 99fa37d150cb27fc0025530747fbd740357659c3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rafael=20Mendon=C3=A7a=20Fran=C3=A7a?= Date: Fri, 13 Dec 2024 19:16:26 +0000 Subject: [PATCH 31/31] Apply all reviews from @p8 Co-authored-by: Petrik de Heus --- guides/source/testing.md | 279 +++++++++++++++++++-------------------- 1 file changed, 135 insertions(+), 144 deletions(-) diff --git a/guides/source/testing.md b/guides/source/testing.md index c09dff15f70cc..0f5fae6563783 100644 --- a/guides/source/testing.md +++ b/guides/source/testing.md @@ -3,7 +3,7 @@ Testing Rails Applications ========================== -This guide covers built-in mechanisms in Rails for testing your application. +This guide explores how to write tests in Rails. After reading this guide, you will know: @@ -35,7 +35,7 @@ creation of a new application. ### Test Setup 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 +using `bin/rails new` _application_name_. If you list the contents of this directory then you will see: ```bash @@ -47,10 +47,14 @@ application_system_test_case.rb controllers/ helpers/ The `helpers`, `mailers`, and `models` directories store tests for [view helpers](#testing-view-helpers), [mailers](#testing-mailers), and -[models](#testing-models), respectively. The `controllers` directory is used for +[models](#testing-models), respectively. + +The `controllers` directory is used for [tests related to controllers](#functional-testing-for-controllers), routes, and views, where HTTP requests will be simulated and assertions made on the -outcomes. The `integration` directory is reserved for [tests that cover +outcomes. + +The `integration` directory is reserved for [tests that cover interactions between controllers](#integration-testing). The `system` test directory holds [system tests](#system-testing), which are @@ -82,9 +86,9 @@ 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`. -NOTE: Your tests are run under `RAILS_ENV=test`. +NOTE: Your tests are run under `RAILS_ENV=test`. This is set by Rails automatically. -### Rails Meets Minitest +### Writing Your First Test We introduced the `bin/rails generate model` command in the [Getting Started with Rails](getting_started.html#mvc-and-you-generating-a-model) guide. @@ -191,18 +195,21 @@ To see how a test failure is reported, you can add a failing test to the will not save without meeting certain criteria; hence, if the article saves successfully, the test will fail, demonstrating a test failure. -```ruby -test "should not save article without title" do - article = Article.new - assert_not article.save +```ruby#4-7 +require "test_helper" + +class ArticleTest < ActiveSupport::TestCase + test "should not save article without title" do + article = Article.new + assert_not article.save + end end ``` -Here is the output if this newly added test is run (with `6` being the line -number where the test is defined): +Here is the output if this newly added test is run: ```bash -$ bin/rails test test/models/article_test.rb:6 +$ bin/rails test test/models/article_test.rb Running 1 tests in a single process (parallelization threshold is 50) Run options: --seed 44656 @@ -211,11 +218,11 @@ Run options: --seed 44656 F Failure: -ArticleTest#test_should_not_save_article_without_title [/path/to/blog/test/models/article_test.rb:6]: +ArticleTest#test_should_not_save_article_without_title [/path/to/blog/test/models/article_test.rb:4]: Expected true to be nil or false -bin/rails test test/models/article_test.rb:6 +bin/rails test test/models/article_test.rb:4 @@ -275,7 +282,7 @@ Finished in 0.027476s, 36.3952 runs/s, 36.3952 assertions/s. The small green dot displayed means that the test has passed successfully. -NOTE: In that process, a test was written first which fails for a desired +TIP: In the process above, a test was written first which fails for a desired functionality, then after, some code was written which adds the functionality. Finally, the test was run again to ensure it passes. This approach to software development is referred to as _Test-Driven Development_ (TDD). @@ -357,7 +364,7 @@ This test should now pass. ### Minitest 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 +Assertions are the foundation blocks 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 @@ -365,41 +372,41 @@ Here's an extract of the assertions you can use with 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?`| -| `assert_error_reported(class) { block }` | Ensures that the error class has been reported, e.g. `assert_error_reported IOError { Rails.error.report(IOError.new("Oops")) }`| -| `assert_no_error_reported { block }` | Ensures that no errors have been reported, e.g. `assert_no_error_reported { perform_service }`| -| `flunk( [msg] )` | Ensures failure. This is useful to explicitly mark a test that isn't finished yet.| +| 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?`| +| `assert_error_reported(class) { block }` | Ensures that the error class has been reported, e.g. `assert_error_reported IOError { Rails.error.report(IOError.new("Oops")) }`| +| `assert_no_error_reported { block }` | Ensures that no errors have been reported, e.g. `assert_no_error_reported { perform_service }`| +| `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 and more up-to-date list, please check the [minitest API @@ -423,46 +430,30 @@ Rails adds some custom assertions of its own to the `minitest` framework: | [`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 extra 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_routing(expected_path, options, defaults={}, extras = {}, message=nil)`][] | Asserts that `path` and `options` match both ways; in other words, it verifies that `path` generates `options` and then that `options` generates `path`. This essentially combines `assert_recognizes` and `assert_generates` into one step. The extras hash allows you to specify options that would normally be provided as a query string to the action. The message parameter allows you to specify a custom error message to display upon failure.| +| [`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 extra 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_routing(expected_path, options, defaults = {}, extras = {}, message = nil)`][] | Asserts that `path` and `options` match both ways; in other words, it verifies that `path` generates `options` and then that `options` generates `path`. This essentially combines `assert_recognizes` and `assert_generates` into one step. The extras hash allows you to specify options that would normally be provided as a query string to the action. The message parameter allows you to specify a custom error message to display upon failure.| | [`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](https://rubydoc.info/gems/rack/Rack/Utils#HTTP_STATUS_CODES-constant) and how their [mapping](https://rubydoc.info/gems/rack/Rack/Utils#SYMBOL_TO_STATUS_CODE-constant) 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`.| +| [`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`.| | [`assert_queries_count(count = nil, include_schema: false, &block)`][] | Asserts that `&block` generates an `int` number of SQL queries.| | [`assert_no_queries(include_schema: false, &block)`][] | Asserts that `&block` generates no SQL queries.| | [`assert_queries_match(pattern, count: nil, include_schema: false, &block)`][] | Asserts that `&block` generates SQL queries that match the pattern.| | [`assert_no_queries_match(pattern, &block)`][] | Asserts that `&block` generates no SQL queries that match the pattern.| -[`assert_difference(expressions, difference = 1, message = nil) {...}`]: - https://api.rubyonrails.org/classes/ActiveSupport/Testing/Assertions.html#method-i-assert_difference) -[`assert_no_difference(expressions, message = nil, &block)`]: - https://api.rubyonrails.org/classes/ActiveSupport/Testing/Assertions.html#method-i-assert_no_difference -[`assert_changes(expressions, message = nil, from:, to:, &block)`]: - https://api.rubyonrails.org/classes/ActiveSupport/Testing/Assertions.html#method-i-assert_changes -[`assert_no_changes(expressions, message = nil, &block)`]: - https://api.rubyonrails.org/classes/ActiveSupport/Testing/Assertions.html#method-i-assert_no_changes -[`assert_nothing_raised { block }`]: - https://api.rubyonrails.org/classes/ActiveSupport/Testing/Assertions.html#method-i-assert_nothing_raised -[`assert_recognizes(expected_options, path, extras={}, message=nil)`]: - https://api.rubyonrails.org/classes/ActionDispatch/Assertions/RoutingAssertions.html#method-i-assert_recognizes -[`assert_generates(expected_path, options, defaults={}, extras = {}, - message=nil)`]: - https://api.rubyonrails.org/classes/ActionDispatch/Assertions/RoutingAssertions.html#method-i-assert_generates -[`assert_routing(expected_path, options, defaults={}, extras = {}, - message=nil)`]: - https://api.rubyonrails.org/classes/ActionDispatch/Assertions/RoutingAssertions.html#method-i-assert_routing -[`assert_response(type, message = nil)`]: - https://api.rubyonrails.org/classes/ActionDispatch/Assertions/ResponseAssertions.html#method-i-assert_response -[`assert_redirected_to(options = {}, message=nil)`]: - https://api.rubyonrails.org/classes/ActionDispatch/Assertions/ResponseAssertions.html#method-i-assert_redirected_to -[`assert_queries_count(count = nil, include_schema: false, &block)`]: - https://api.rubyonrails.org/classes/ActiveRecord/Assertions/QueryAssertions.html#method-i-assert_queries_count -[`assert_no_queries(include_schema: false, &block)`]: - https://api.rubyonrails.org/classes/ActiveRecord/Assertions/QueryAssertions.html#method-i-assert_no_queries -[`assert_queries_match(pattern, count: nil, include_schema: false, &block)`]: - https://api.rubyonrails.org/classes/ActiveRecord/Assertions/QueryAssertions.html#method-i-assert_queries_match -[`assert_no_queries_match(pattern, &block)`]: - https://api.rubyonrails.org/classes/ActiveRecord/Assertions/QueryAssertions.html#method-i-assert_no_queries_match +[`assert_difference(expressions, difference = 1, message = nil) {...}`]: https://api.rubyonrails.org/classes/ActiveSupport/Testing/Assertions.html#method-i-assert_difference) +[`assert_no_difference(expressions, message = nil, &block)`]: https://api.rubyonrails.org/classes/ActiveSupport/Testing/Assertions.html#method-i-assert_no_difference +[`assert_changes(expressions, message = nil, from:, to:, &block)`]: https://api.rubyonrails.org/classes/ActiveSupport/Testing/Assertions.html#method-i-assert_changes +[`assert_no_changes(expressions, message = nil, &block)`]: https://api.rubyonrails.org/classes/ActiveSupport/Testing/Assertions.html#method-i-assert_no_changes +[`assert_nothing_raised { block }`]: https://api.rubyonrails.org/classes/ActiveSupport/Testing/Assertions.html#method-i-assert_nothing_raised +[`assert_recognizes(expected_options, path, extras = {}, message = nil)`]: https://api.rubyonrails.org/classes/ActionDispatch/Assertions/RoutingAssertions.html#method-i-assert_recognizes +[`assert_generates(expected_path, options, defaults = {}, extras = {}, message = nil)`]: https://api.rubyonrails.org/classes/ActionDispatch/Assertions/RoutingAssertions.html#method-i-assert_generates +[`assert_routing(expected_path, options, defaults = {}, extras = {}, message = nil)`]: https://api.rubyonrails.org/classes/ActionDispatch/Assertions/RoutingAssertions.html#method-i-assert_routing +[`assert_response(type, message = nil)`]: https://api.rubyonrails.org/classes/ActionDispatch/Assertions/ResponseAssertions.html#method-i-assert_response +[`assert_redirected_to(options = {}, message = nil)`]: https://api.rubyonrails.org/classes/ActionDispatch/Assertions/ResponseAssertions.html#method-i-assert_redirected_to +[`assert_queries_count(count = nil, include_schema: false, &block)`]: https://api.rubyonrails.org/classes/ActiveRecord/Assertions/QueryAssertions.html#method-i-assert_queries_count +[`assert_no_queries(include_schema: false, &block)`]: https://api.rubyonrails.org/classes/ActiveRecord/Assertions/QueryAssertions.html#method-i-assert_no_queries +[`assert_queries_match(pattern, count: nil, include_schema: false, &block)`]: https://api.rubyonrails.org/classes/ActiveRecord/Assertions/QueryAssertions.html#method-i-assert_queries_match +[`assert_no_queries_match(pattern, &block)`]: https://api.rubyonrails.org/classes/ActiveRecord/Assertions/QueryAssertions.html#method-i-assert_no_queries_match You'll see the usage of some of these assertions in the next chapter. @@ -483,54 +474,9 @@ 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 your tests. -NOTE: For more information on `minitest`, refer to the [minitest +TIP: For more information on `minitest`, refer to the [minitest documentation](http://docs.seattlerb.org/minitest). -### Transactions - -By default, Rails automatically wraps tests in a database transaction that is -rolled back once completed. This makes tests independent of each other and means -that changes to the database are only visible within a single test. - -```ruby -class MyTest < ActiveSupport::TestCase - test "newly created users are active by default" do - # Since the test is implicitly wrapped in a database transaction, the user - # created here won't be seen by other tests. - assert User.create.active? - end -end -``` - -The method -[`ActiveRecord::Base.current_transaction`](https://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html#method-i-current_transaction) -still acts as intended, though: - -```ruby -class MyTest < ActiveSupport::TestCase - test "Active Record current_transaction method works as expected" do - # The implicit transaction around tests does not interfere with the - # application-level semantics of the current_transaction. - assert User.current_transaction.blank? - end -end -``` - -If there are [multiple writing databases](active_record_multiple_databases.html) -in place, tests are wrapped in as many respective transactions, and all of them -are rolled back. - -#### Opting-out of Test Transactions - -Individual test cases can opt-out: - -```ruby -class MyTest < ActiveSupport::TestCase - # No implicit database transaction wraps the tests in this test case. - self.use_transactional_tests = false -end -``` - ### The Rails Test Runner We can run all of our tests at once by using the `bin/rails test` command. @@ -673,7 +619,7 @@ documentation](https://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html) #### What are Fixtures? -_Fixtures_ is a fancy word for sample data. Fixtures allow you to populate your +_Fixtures_ is a fancy word for a consistent set of test 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. @@ -685,6 +631,7 @@ Fixtures are stored in your `test/fixtures` directory. #### YAML +[YAML](https://en.wikipedia.org/wiki/YAML) is a human-readable data serialization language. 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`). @@ -713,15 +660,15 @@ a reference node between two different fixtures. Here's an example with a ```yaml # test/fixtures/categories.yml -about: - name: About +web_frameworks: + name: Web Frameworks ``` ```yaml # test/fixtures/articles.yml first: title: Welcome to Rails! - category: about + category: web_frameworks ``` ```yaml @@ -733,9 +680,9 @@ first_content: ``` Notice the `category` key of the `first` Article found in -`fixtures/articles.yml` has a value of `about`, and that the `record` key of the +`fixtures/articles.yml` has a value of `web_frameworks`, and that the `record` key of the `first_content` entry found in `fixtures/action_text/rich_texts.yml` has a value -of `first (Article)`. This hints to Active Record to load the Category `about` +of `first (Article)`. This hints to Active Record to load the Category `web_frameworks` found in `fixtures/categories.yml` for the former, and Action Text to load the Article `first` found in `fixtures/articles.yml` for the latter. @@ -832,7 +779,7 @@ users(:david) # this will return the property for david called id users(:david).id -# methods available to the User class can also be accessed +# methods available to the User object can also be accessed david = users(:david) david.call(david.partner) ``` @@ -845,6 +792,50 @@ example: users(:david, :steve) ``` +### Transactions + +By default, Rails automatically wraps tests in a database transaction that is +rolled back once completed. This makes tests independent of each other and means +that changes to the database are only visible within a single test. + +```ruby +class MyTest < ActiveSupport::TestCase + test "newly created users are active by default" do + # Since the test is implicitly wrapped in a database transaction, the user + # created here won't be seen by other tests. + assert User.create.active? + end +end +``` + +The method +[`ActiveRecord::Base.current_transaction`](https://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html#method-i-current_transaction) +still acts as intended, though: + +```ruby +class MyTest < ActiveSupport::TestCase + test "Active Record current_transaction method works as expected" do + # The implicit transaction around tests does not interfere with the + # application-level semantics of the current_transaction. + assert User.current_transaction.blank? + end +end +``` + +If there are [multiple writing databases](active_record_multiple_databases.html) +in place, tests are wrapped in as many respective transactions, and all of them +are rolled back. + +#### Opting-out of Test Transactions + +Individual test cases can opt-out: + +```ruby +class MyTest < ActiveSupport::TestCase + # No implicit database transaction wraps the tests in this test case. + self.use_transactional_tests = false +end +``` Testing Models -------------- @@ -943,7 +934,7 @@ end ``` In the `test_should_get_index` test, Rails simulates a request on the action -called `index`, making sure the request was successful and also ensuring that +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 @@ -1003,7 +994,7 @@ end You can now run this test and it will pass. NOTE: If you followed the steps in the [Basic -Authentication](getting_started.html#basic-authentication) section, you'll need +Authentication](getting_started.html#adding-authentication) section, you'll need to add authorization to every request header to get all the tests passing: ```ruby @@ -1023,7 +1014,7 @@ request. There are 6 request types supported in Rails functional tests: * `delete` All of the request types have equivalent methods that you can use. In a typical -C.R.U.D. application you'll be using `post`, `get`, `put`, and `delete` most +CRUD application you'll be using `post`, `get`, `put`, and `delete` most often. NOTE: Functional tests do not verify whether the specified request type is @@ -1225,14 +1216,14 @@ 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. + # Reload article to refresh data and assert that title is updated. article.reload assert_equal "updated", article.title end ``` Notice that there is some duplication in these three tests - they both access -the same article fixture data. It is possible to D.R.Y. ('Don't Repeat +the same article fixture data. It is possible to DRY ('Don't Repeat Yourself') the implementation by using the `setup` and `teardown` methods provided by `ActiveSupport::Callbacks`.