Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Ruby Build a Todo List Application with Rails 4 Build a Todo List Application with Rails 4 Viewing Todo Lists

todo_items/show view testing

Why this rspec test doesn't work (throws "undefined method `todo_items' for nil:NilClass")

require 'spec_helper'
describe "todo_lists/show" do
  before(:each) do
    @todo_list = assign(:todo_list, stub_model(TodoList,
      :title => "Title",
      :description => "MyText"
    ))
  end

  @todo_list.todo_items.create(content: 'Eggs', completed_at: 5.minutes.ago)
  @todo_list.todo_items.create(content: 'Milk')
  it "show completed items in ul#completed_item " do
    within "ul#completed_items" do
      expect(page).to have_content('Eggs')
      expect(page).to not_have_content('Milk')
    end
  end
end

...while if I put the create statements inside the it example it seems correct?

require 'spec_helper'
describe "todo_lists/show" do
  before(:each) do
    @todo_list = assign(:todo_list, stub_model(TodoList,
      :title => "Title",
      :description => "MyText"
    ))
  end

  it "show completed items in ul#completed_item " do
    @todo_list.todo_items.create(content: 'Eggs', completed_at: 5.minutes.ago)
    @todo_list.todo_items.create(content: 'Milk')
    within "ul#completed_items" do
      expect(page).to have_content('Eggs')
      expect(page).to not_have_content('Milk')
    end
  end
end

1 Answer

David O' Rojo
David O' Rojo
11,050 Points

The first code shows an error because @todo_list is defined inside the before block scope. This makes @todo_list not available on the main body of the describe block scope, but it is available for the scope of the examples (it) so the second code works as expected.

Check the answers to the question How do instance variables on RSpec work.