Basic TDD in Rails : Display Validation Error Messages

Objective


To display error message to the user when the validation fails.

Steps


Step 1

Add a new feature test in features/manage_articles_spec.rb:

  it 'should display error message to the user' do
    visit articles_path

    click_link 'New Article'
    fill_in "Title", with: 'Test Article'
    click_button 'Submit'

    expect(page).to have_text("Description can't be blank")      
  end

Step 2

Run the test : rspec spec/features/manage_articles_spec.rb.

The error is:

   Failure/Error: Unable to find matching line from backtrace
     ActionView::Template::Error:
       undefined method `errors' for nil:NilClass

Step 3

Change the article to instance variable in the create action as follows:

  def create
    allowed_params = params.require(:article).permit(:title, :description)
    @article = Article.new(allowed_params)

    if @article.save
      redirect_to articles_path
    else
      render :new
    end
  end

Run the test. It will fail.

Step 4

Add the code to display validation error message to the top of the new.html.erb:

<% if @article.errors.any? %>
  <h2><%= pluralize(@article.errors.count, "error") %> prohibited
    this article from being saved:</h2>

  <ul>
  <% @article.errors.full_messages.each do |m| %>
    <li><%= m %></li>
  <% end %>
  </ul>
<% end %>

Run the test. It will pass.

Exercise


Write a feature spec to test for validation failure due to missing title.

Summary


In this lesson you learned how to write a test for validation failures.


Related Articles


Software Compatibility Best Practices

I spoke to some of the most talented and experienced software developers. I have created a guide that is filled with valuable insights and actionable ideas to boost developer productivity.

You will gain a better understanding of what's working well for other developers and how they address the software compatibility problems.

Get the Guide Now