Form submit in a Rails functional test

Getting started with functional tests in Ruby on Rails.

I’m new to testing and documentation for the built-in Rails testing seems scarce so I’ll write down what I learn in the process.

Submitting a form in a test

In a functional test you test the controller. A controller is responsible for the incoming requests and the response with a rendered view. If you want to test the creation of an object you’ll need a way to fill the form and send the data to the controller.

Imagine the following functional test to create new articles for our blog (example in Rails 3):

require 'test_helper'
class ArticlesControllerTest < ActionController::TestCase
  test "create a new blog article" do
    post :create, :article => {:title => "Lorem", :content => "Ipsum dolor sit."}
    article = assigns(:article)
    assert_not_nil article
    assert article.errors.count == 0
    assert_equal "Article successfully created.", flash[:notice]

As this test is in the articles_controller_test.rb file Rails knows to call the article create action with a POST request. The controller will handle the request and will render or redirect to a new page with a flash message, this we can test.

The first line is key here. It sends the parameters in the form to the controller. The second line assigns the article instance variable. The next lines are some assertions I added to test if the request succeeded, add at will.

More resources