diff options
Diffstat (limited to 'guides/source/testing.md')
-rw-r--r-- | guides/source/testing.md | 191 |
1 files changed, 95 insertions, 96 deletions
diff --git a/guides/source/testing.md b/guides/source/testing.md index 36d37f3af0..c01b2e575a 100644 --- a/guides/source/testing.md +++ b/guides/source/testing.md @@ -49,7 +49,9 @@ The `test_helper.rb` file holds the default configuration for your tests. ### The Low-Down on Fixtures -For good tests, you'll need to give some thought to setting up test data. In Rails, you can handle this by defining and customizing fixtures. +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 [fixture api documentation](http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html). #### What Are Fixtures? @@ -94,6 +96,12 @@ one: category: about ``` +Note: For associations to reference one another by name, you cannot specify the `id:` + attribute on the fixtures. Rails will auto assign a primary key to be consistent between + runs. If you manually specify an `id:` attribute, this behavior will not work. For more + information on this assocation behavior please read the + [fixture api documentation](http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html). + #### ERB'in It Up ERB allows you to embed Ruby code within templates. The YAML fixture format is pre-processed with ERB when Rails loads fixtures. This allows you to use Ruby to help you generate some sample data. For example, the following code generates a thousand users: @@ -134,27 +142,27 @@ Unit Testing your Models In Rails, models tests are what you write to test your models. -For this guide we will be using Rails _scaffolding_. It will create the model, a migration, controller and views for the new resource in a single operation. It will also create a full test suite following Rails best practices. I will be using examples from this generated code and will be supplementing it with additional examples where necessary. +For this guide we will be using Rails _scaffolding_. It will create the model, a migration, controller and views for the new resource in a single operation. It will also create a full test suite following Rails best practices. We will be using examples from this generated code and will be supplementing it with additional examples where necessary. NOTE: For more information on Rails <i>scaffolding</i>, refer to [Getting Started with Rails](getting_started.html) When you use `rails generate scaffold`, for a resource among other things it creates a test stub in the `test/models` folder: ```bash -$ rails generate scaffold post title:string body:text +$ bin/rails generate scaffold article title:string body:text ... -create app/models/post.rb -create test/models/post_test.rb -create test/fixtures/posts.yml +create app/models/article.rb +create test/models/article_test.rb +create test/fixtures/articles.yml ... ``` -The default test stub in `test/models/post_test.rb` looks like this: +The default test stub in `test/models/article_test.rb` looks like this: ```ruby require 'test_helper' -class PostTest < ActiveSupport::TestCase +class ArticleTest < ActiveSupport::TestCase # test "the truth" do # assert true # end @@ -170,15 +178,15 @@ require 'test_helper' As you know by now, `test_helper.rb` specifies the default configuration to run our tests. This is included with all the tests, so any methods added to this file are available to all your tests. ```ruby -class PostTest < ActiveSupport::TestCase +class ArticleTest < ActiveSupport::TestCase ``` -The `PostTest` class defines a _test case_ because it inherits from `ActiveSupport::TestCase`. `PostTest` thus has all the methods available from `ActiveSupport::TestCase`. You'll see those methods a little later in this guide. +The `ArticleTest` class defines a _test case_ because it inherits from `ActiveSupport::TestCase`. `ArticleTest` thus has all the methods available from `ActiveSupport::TestCase`. You'll see those methods a little later in this guide. -Any method defined within a class inherited from `MiniTest::Unit::TestCase` -(which is the superclass of `ActiveSupport::TestCase`) that begins with `test` (case sensitive) is simply called a test. So, `test_password`, `test_valid_password` and `testValidPassword` all are legal test names and are run automatically when the test case is run. +Any method defined within a class inherited from `Minitest::Test` +(which is the superclass of `ActiveSupport::TestCase`) that begins with `test_` (case sensitive) is simply called a test. So, `test_password` and `test_valid_password` are legal test names and are run automatically when the test case is run. -Rails adds a `test` method that takes a test name and a block. It generates a normal `MiniTest::Unit` test with method names prefixed with `test_`. So, +Rails adds a `test` method that takes a test name and a block. It generates a normal `Minitest::Unit` test with method names prefixed with `test_`. So, ```ruby test "the truth" do @@ -220,7 +228,7 @@ In order to run your tests, your test database will need to have the current str Running a test is as simple as invoking the file containing the test cases through `rake test` command. ```bash -$ rake test test/models/post_test.rb +$ bin/rake test test/models/article_test.rb . Finished tests in 0.009262s, 107.9680 tests/s, 107.9680 assertions/s. @@ -231,7 +239,7 @@ Finished tests in 0.009262s, 107.9680 tests/s, 107.9680 assertions/s. You can also run a particular test method from the test case by running the test and providing the `test method name`. ```bash -$ rake test test/models/post_test.rb test_the_truth +$ bin/rake test test/models/article_test.rb test_the_truth . Finished tests in 0.009064s, 110.3266 tests/s, 110.3266 assertions/s. @@ -243,25 +251,25 @@ This will run all test methods from the test case. Note that `test_helper.rb` is The `.` (dot) above indicates a passing test. When a test fails you see an `F`; when a test throws an error you see an `E` in its place. The last line of the output is the summary. -To see how a test failure is reported, you can add a failing test to the `post_test.rb` test case. +To see how a test failure is reported, you can add a failing test to the `article_test.rb` test case. ```ruby -test "should not save post without title" do - post = Post.new - assert_not post.save +test "should not save article without title" do + article = Article.new + assert_not article.save end ``` Let us run this newly added test. ```bash -$ rake test test/models/post_test.rb test_should_not_save_post_without_title +$ bin/rake test test/models/article_test.rb test_should_not_save_article_without_title F Finished tests in 0.044632s, 22.4054 tests/s, 22.4054 assertions/s. 1) Failure: -test_should_not_save_post_without_title(PostTest) [test/models/post_test.rb:6]: +test_should_not_save_article_without_title(ArticleTest) [test/models/article_test.rb:6]: Failed assertion, no message given. 1 tests, 1 assertions, 1 failures, 0 errors, 0 skips @@ -270,9 +278,9 @@ Failed assertion, no message given. In the output, `F` denotes a failure. You can see the corresponding trace shown under `1)` along with the name of the failing test. The next few lines contain the stack trace followed by a message which mentions the actual value and the expected value by the assertion. The default assertion messages provide just enough information to help pinpoint the error. To make the assertion failure message more readable, every assertion provides an optional message parameter, as shown here: ```ruby -test "should not save post without title" do - post = Post.new - assert_not post.save, "Saved the post without a title" +test "should not save article without title" do + article = Article.new + assert_not article.save, "Saved the article without a title" end ``` @@ -280,14 +288,14 @@ Running this test shows the friendlier assertion message: ```bash 1) Failure: -test_should_not_save_post_without_title(PostTest) [test/models/post_test.rb:6]: -Saved the post without a title +test_should_not_save_article_without_title(ArticleTest) [test/models/article_test.rb:6]: +Saved the article without a title ``` Now to get this test to pass we can add a model level validation for the _title_ field. ```ruby -class Post < ActiveRecord::Base +class Article < ActiveRecord::Base validates :title, presence: true end ``` @@ -295,7 +303,7 @@ end Now the test should pass. Let us verify by running the test again: ```bash -$ rake test test/models/post_test.rb test_should_not_save_post_without_title +$ bin/rake test test/models/article_test.rb test_should_not_save_article_without_title . Finished tests in 0.047721s, 20.9551 tests/s, 20.9551 assertions/s. @@ -320,15 +328,15 @@ end Now you can see even more output in the console from running the tests: ```bash -$ rake test test/models/post_test.rb test_should_report_error +$ bin/rake test test/models/article_test.rb test_should_report_error E Finished tests in 0.030974s, 32.2851 tests/s, 0.0000 assertions/s. 1) Error: -test_should_report_error(PostTest): -NameError: undefined local variable or method `some_undefined_variable' for #<PostTest:0x007fe32e24afe0> - test/models/post_test.rb:10:in `block in <class:PostTest>' +test_should_report_error(ArticleTest): +NameError: undefined local variable or method `some_undefined_variable' for #<ArticleTest:0x007fe32e24afe0> + test/models/article_test.rb:10:in `block in <class:ArticleTest>' 1 tests, 0 assertions, 0 failures, 1 errors, 0 skips ``` @@ -345,7 +353,7 @@ backtrace. simply set the `BACKTRACE` environment variable to enable this behavior: ```bash -$ BACKTRACE=1 rake test test/models/post_test.rb +$ BACKTRACE=1 bin/rake test test/models/article_test.rb ``` ### What to Include in Your Unit Tests @@ -393,7 +401,7 @@ NOTE: Creating your own assertions is an advanced topic that we won't cover in t ### Rails Specific Assertions -Rails adds some custom assertions of its own to the `test/unit` framework: +Rails adds some custom assertions of its own to the `minitest` framework: | Assertion | Purpose | | --------------------------------------------------------------------------------- | ------- | @@ -422,26 +430,26 @@ You should test for things such as: * was the correct object stored in the response template? * was the appropriate message displayed to the user in the view? -Now that we have used Rails scaffold generator for our `Post` resource, it has already created the controller code and tests. You can take look at the file `posts_controller_test.rb` in the `test/controllers` directory. +Now that we have used Rails scaffold generator for our `Article` resource, it has already created the controller code and tests. You can take look at the file `articles_controller_test.rb` in the `test/controllers` directory. -Let me take you through one such test, `test_should_get_index` from the file `posts_controller_test.rb`. +Let me take you through one such test, `test_should_get_index` from the file `articles_controller_test.rb`. ```ruby -class PostsControllerTest < ActionController::TestCase +class ArticlesControllerTest < ActionController::TestCase test "should get index" do get :index assert_response :success - assert_not_nil assigns(:posts) + assert_not_nil assigns(:articles) 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 it assigns a valid `posts` instance variable. +In the `test_should_get_index` test, Rails simulates a request on the action called `index`, making sure the request was successful and also ensuring that it assigns a valid `articles` instance variable. The `get` method kicks off the web request and populates the results into the response. It accepts 4 arguments: * The action of the controller you are requesting. This can be in the form of a string or a symbol. -* An optional hash of request parameters to pass into the action (eg. query string parameters or post variables). +* An optional hash of request parameters to pass into the action (eg. query string parameters or article variables). * An optional hash of session variables to pass along with the request. * An optional hash of flash values. @@ -457,17 +465,17 @@ Another example: Calling the `:view` action, passing an `id` of 12 as the `param get(:view, {'id' => '12'}, nil, {'message' => 'booya!'}) ``` -NOTE: If you try running `test_should_create_post` test from `posts_controller_test.rb` it will fail on account of the newly added model level validation and rightly so. +NOTE: If you try running `test_should_create_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_post` test in `posts_controller_test.rb` so that all our test pass: +Let us modify `test_should_create_article` test in `articles_controller_test.rb` so that all our test pass: ```ruby -test "should create post" do - assert_difference('Post.count') do - post :create, post: {title: 'Some title'} +test "should create article" do + assert_difference('Article.count') do + post :create, article: {title: 'Some title'} end - assert_redirected_to post_path(assigns(:post)) + assert_redirected_to article_path(assigns(:article)) end ``` @@ -576,12 +584,12 @@ is the correct way to assert for the layout when the view renders a partial with Here's another example that uses `flash`, `assert_redirected_to`, and `assert_difference`: ```ruby -test "should create post" do - assert_difference('Post.count') do - post :create, post: {title: 'Hi', body: 'This is my first post.'} +test "should create article" do + assert_difference('article.count') do + post :create, article: {title: 'Hi', body: 'This is my first article.'} end - assert_redirected_to post_path(assigns(:post)) - assert_equal 'Post was successfully created.', flash[:notice] + assert_redirected_to article_path(assigns(:article)) + assert_equal 'Article was successfully created.', flash[:notice] end ``` @@ -653,7 +661,7 @@ Integration tests are used to test the interaction among any number of controlle Unlike Unit and Functional tests, integration tests have to be explicitly created under the 'test/integration' folder within your application. Rails provides a generator to create an integration test skeleton for you. ```bash -$ rails generate integration_test user_flows +$ bin/rails generate integration_test user_flows exists test/integration/ create test/integration/user_flows_test.rb ``` @@ -699,8 +707,6 @@ A simple integration test that exercises multiple controllers: require 'test_helper' class UserFlowsTest < ActionDispatch::IntegrationTest - fixtures :users - test "login and browse site" do # login via https https! @@ -712,7 +718,7 @@ class UserFlowsTest < ActionDispatch::IntegrationTest assert_equal 'Welcome david!', flash[:notice] https!(false) - get "/posts/all" + get "/articles/all" assert_response :success assert assigns(:products) end @@ -727,10 +733,7 @@ Here's an example of multiple sessions and custom DSL in an integration test require 'test_helper' class UserFlowsTest < ActionDispatch::IntegrationTest - fixtures :users - test "login and browse site" do - # User david logs in david = login(:david) # User guest logs in @@ -793,57 +796,53 @@ when you initiate a Rails project. | `rake test:all:db` | Runs all tests quickly by merging all types and resetting db | -Brief Note About `MiniTest` +Brief Note About `Minitest` ----------------------------- -Ruby ships with a vast Standard Library for all common use-cases including testing. Ruby 1.8 provided `Test::Unit`, a framework for unit testing in Ruby. All the basic assertions discussed above are actually defined in `Test::Unit::Assertions`. The class `ActiveSupport::TestCase` which we have been using in our unit and functional tests extends `Test::Unit::TestCase`, allowing -us to use all of the basic assertions in our tests. - -Ruby 1.9 introduced `MiniTest`, an updated version of `Test::Unit` which provides a backwards compatible API for `Test::Unit`. You could also use `MiniTest` in Ruby 1.8 by installing the `minitest` gem. +Ruby ships with a vast Standard Library for all common use-cases including testing. Since version 1.9, Ruby provides `Minitest`, a framework for testing. All the basic assertions such as `assert_equal` discussed above are actually defined in `Minitest::Assertions`. The classes `ActiveSupport::TestCase`, `ActionController::TestCase`, `ActionMailer::TestCase`, `ActionView::TestCase` and `ActionDispatch::IntegrationTest` - which we have been inheriting in our test classes - include `Minitest::Assertions`, allowing us to use all of the basic assertions in our tests. -NOTE: For more information on `Test::Unit`, refer to [test/unit Documentation](http://ruby-doc.org/stdlib/libdoc/test/unit/rdoc/) -For more information on `MiniTest`, refer to [Minitest](http://www.ruby-doc.org/stdlib-1.9.3/libdoc/minitest/unit/rdoc/) +NOTE: For more information on `Minitest`, refer to [Minitest](http://ruby-doc.org/stdlib-2.1.0/libdoc/minitest/rdoc/MiniTest.html) Setup and Teardown ------------------ -If you would like to run a block of code before the start of each test and another block of code after the end of each test you have two special callbacks for your rescue. Let's take note of this by looking at an example for our functional test in `Posts` controller: +If you would like to run a block of code before the start of each test and another block of code after the end of each test you have two special callbacks for your rescue. Let's take note of this by looking at an example for our functional test in `Articles` controller: ```ruby require 'test_helper' -class PostsControllerTest < ActionController::TestCase +class ArticlesControllerTest < ActionController::TestCase # called before every single test def setup - @post = posts(:one) + @article = articles(:one) end # called after every single test def teardown - # as we are re-initializing @post before every test + # as we are re-initializing @article before every test # setting it to nil here is not essential but I hope # you understand how you can use the teardown method - @post = nil + @article = nil end - test "should show post" do - get :show, id: @post.id + test "should show article" do + get :show, id: @article.id assert_response :success end - test "should destroy post" do - assert_difference('Post.count', -1) do - delete :destroy, id: @post.id + test "should destroy article" do + assert_difference('Article.count', -1) do + delete :destroy, id: @article.id end - assert_redirected_to posts_path + assert_redirected_to articles_path end end ``` -Above, the `setup` method is called before each test and so `@post` is available for each of the tests. Rails implements `setup` and `teardown` as `ActiveSupport::Callbacks`. Which essentially means you need not only use `setup` and `teardown` as methods in your tests. You could specify them by using: +Above, the `setup` method is called before each test and so `@article` is available for each of the tests. Rails implements `setup` and `teardown` as `ActiveSupport::Callbacks`. Which essentially means you need not only use `setup` and `teardown` as methods in your tests. You could specify them by using: * a block * a method (like in the earlier example) @@ -855,38 +854,38 @@ Let's see the earlier example by specifying `setup` callback by specifying a met ```ruby require 'test_helper' -class PostsControllerTest < ActionController::TestCase +class ArticlesControllerTest < ActionController::TestCase # called before every single test - setup :initialize_post + setup :initialize_article # called after every single test def teardown - @post = nil + @article = nil end - test "should show post" do - get :show, id: @post.id + test "should show article" do + get :show, id: @article.id assert_response :success end - test "should update post" do - patch :update, id: @post.id, post: {} - assert_redirected_to post_path(assigns(:post)) + test "should update article" do + patch :update, id: @article.id, article: {} + assert_redirected_to article_path(assigns(:article)) end - test "should destroy post" do - assert_difference('Post.count', -1) do - delete :destroy, id: @post.id + test "should destroy article" do + assert_difference('Article.count', -1) do + delete :destroy, id: @article.id end - assert_redirected_to posts_path + assert_redirected_to articles_path end private - def initialize_post - @post = posts(:one) + def initialize_article + @article = articles(:one) end end ``` @@ -894,11 +893,11 @@ end Testing Routes -------------- -Like everything else in your Rails application, it is recommended that you test your routes. An example test for a route in the default `show` action of `Posts` controller above should look like: +Like everything else in your Rails application, it is recommended that you test your routes. An example test for a route in the default `show` action of `Articles` controller above should look like: ```ruby -test "should route to post" do - assert_routing '/posts/1', {controller: "posts", action: "show", id: "1"} +test "should route to article" do + assert_routing '/articles/1', {controller: "articles", action: "show", id: "1"} end ``` @@ -1011,7 +1010,7 @@ located under the `test/helpers` directory. Rails provides a generator which generates both the helper and the test file: ```bash -$ rails generate helper User +$ bin/rails generate helper User create app/helpers/user_helper.rb invoke test_unit create test/helpers/user_helper_test.rb @@ -1046,7 +1045,7 @@ access to Rails' helper methods such as `link_to` or `pluralize`. Other Testing Approaches ------------------------ -The built-in `test/unit` based testing is not the only way to test Rails applications. Rails developers have come up with a wide variety of other approaches and aids for testing, including: +The built-in `minitest` based testing is not the only way to test Rails applications. Rails developers have come up with a wide variety of other approaches and aids for testing, including: * [NullDB](http://avdi.org/projects/nulldb/), a way to speed up testing by avoiding database use. * [Factory Girl](https://github.com/thoughtbot/factory_girl/tree/master), a replacement for fixtures. |