Understand the Arrange-Act-Assert Pattern

❮ Back Next ❯

A key goal of this activity is to learn to write automated tests. Developers typically write automated tests as they create new code. The tests can be run at the time that the new code is written to help ensure that the code is free of bugs. The tests are saved along with the project code, so they can be run periodically to help detect any new bugs that creep into the code.

Thanks to modern testing frameworks and tools, writing an automated test often simply amounts to adding a new method to a class. Testing tools enable running these methods (e.g., by entering a command, like rails test, in the terminal).

Each automated test we write commonly performs three steps, which follow the Arrange-Act-Assert pattern:

For example, here is a Rails controller test that illustrates the Arrange-Act-Assert pattern:

  test "should show article" do
    # Arrange: Retrieve an article test fixture.
    article = articles(:one)

    # Act: Simulate an HTTP GET request that should cause the article controller's `show` action to execute.
    get article_url(article)
    
    # Assert: Check whether the HTTP response contained a success status code and whether the rendered page contained an `h1` HTML element with the title of the article.
    assert_response :success
    assert_select 'h1', text: article.title
  end

When this test is run, if the assertions hold true, the test will be considered to have passed. However, if either assertion does not hold (e.g., if the response contained a 404 Not Found status code), the test will be considered to have failed.


❮ Back Next ❯