Basic TDD in Rails : Display Validation Error Messages


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


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")      

Step 2

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

The error is:

   Failure/Error: Unable to find matching line from backtrace
       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 =

      redirect_to articles_path
      render :new

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>

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

Run the test. It will pass.


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


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