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


Ace the Technical Interview

  • Easily find the gaps in your knowledge
  • Get customized lessons based on where you are
  • Take consistent action everyday
  • Builtin accountability to keep you on track
  • You will solve bigger problems over time
  • Get the job of your dreams

Take the 30 Day Coding Skills Challenge

Gain confidence to attend the interview

No spam ever. Unsubscribe anytime.