Basic TDD in Rails : Display Validation Error Messages
To display error message to the user when the validation fails.
Add a new feature test in
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
Run the test :
The error is:
Failure/Error: Unable to find matching line from backtrace ActionView::Template::Error: undefined method `errors' for nil:NilClass
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.
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.
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.
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.