Rspec error for failing test different than the error seen in browser

While going through the ‘Creating the First Todo’ part of the Test Driven Rails workshop, i added the following in my spec/features/user_creates_todo_spec.rb.

require 'rails_helper'

feature 'User creates todo' do 
	scenario 'successfully' do
		visit root_path
		
		click_on 'Add a new todo'
		fill_in 'Title', with: 'Buy milk'
		click_on 'Submit'

		expect(page).to have_css '.todos li', text: 'Buy milk'
	end
end

Then in my app/views/todos/index.html.erb, i added the following:

<%= link_to "Add a new todo", new_todo_path %>

When i run rspec spec/features/user_creates_todo_spec.rb,the test fails with an error Capybara::ElementNotFound: Unable to find link or button “Add a new todo”

However, as per the tutorial im expecting the error to be: Undefined local variable or method ‘new_todo_path’ . But when i run the rails server and navigate to the root path from the browser i see the undefined local variable or method ‘new_todo_path’ error. So, why is it that rspec is showing a different error even though i have the link added to the page ?

Thanks

There are a few things which might cause this. Add a call to puts page.body before the click_on and you’ll be able to see what’s actually on the page.

Is todos_path set up to be your root url?

One of the best ways to debug feature specs is to use the save_and_open_page method! It is really helpful for checking out what your test is seeing.

I agree with @Jurre that it seems like you haven’t set up todos_path as your root_url, which is why the link is not being found (since that is where your test is looking for the link)

1 Like

Thanks for the replies. I do have the root path set in my config/routes.rb, as follows:

root to: 'todos#index'

But still capybara does not show the rails exception when i run the test. As has been correctly pointed out i can do a puts page.body to see the exception raised or the save_and_open_page method but isnt capybara supposed to show the ‘Undefined local variable or method’ error as we see in the videos of the test driven rails course ?

Thanks

For sure capybara was supposed to show the ‘Undefined local variable or method’. You can use the puts page.body or save_and_open_page to see the page that was rendered. I guess the error was not raised because the default rails root page has been rendered instead of the expected page.

When you use save_and_open_page do you see your link in the rendered HTML?