Basic TDD in Rails : Writing a Feature Test

Objective


  • To write a feature test for the article index page.

Steps


Step 1

Add the second test:

  scenario 'has link to my blog' do
    visit root_path

    click_link 'My Blog'

    expect(page).to have_text('Listing Articles')  
  end

Step 2

Run the test.

$ rspec spec/features/home_page_spec.rb 

Step 3

The error is :

 1) Home Page has link to my blog
     Failure/Error: click_link 'My Blog'
     Capybara::ElementNotFound:
       Unable to find link "My Blog"

Step 4

Add the hyper link to app/views/welcome/index.html.erb

<%= link_to 'My Blog', articles_path %>

Step 5

Run the test

$ rspec spec/features/home_page_spec.rb 

Step 6

The error is :

undefined local variable or method `articles_path' for class

Step 7

Add

resources :articles 

to the routes.rb

Step 8

Run the test.

$ rspec spec/features/home_page_spec.rb 

Step 9

The error is:

1) Home Page has link to my blog
     Failure/Error: Unable to find matching line from backtrace
     ActionController::RoutingError:
       uninitialized constant ArticlesController

Step 10

Create the articles controller.

$ rails g controller articles index

Step 11

Run the test.

$ rspec spec/features/home_page_spec.rb 

Step 12

The error is:

1) Home Page has link to my blog
     Failure/Error: expect(page).to have_text('Listing Articles')
       expected to find text "Listing Articles" in "Articles#index Find me in app/views/articles/index.html.erb"
     # ./spec/features/home_page_spec.rb:16:in `block (2 levels) in <top (required)>'

Step 13

Add

<h1>Listing Articles</h1> 

to the articles/index.html.erb

Step 14

Run the test. It will pass.

Summary


In this lesson, you learned how to write a feature test using Capybara. We made changes to the view layer, the routes, the controller and finally the view. They were all driven by the test.


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.