Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial![](https://ecs-static.teamtreehouse.com/assets/views/marketing/shared/community-banner-white-47072046c51352fe6a69f5e691ff5700b28bb11d45197d7bdf066d9ea3f72d0c.webp)
![Unsubscribed User](https://secure.gravatar.com/avatar/2e0e4e96a7eb52e94abd6cfb4ef8b14d?s=96&d=https%3A%2F%2Fecs-static.teamtreehouse.com%2Fassets%2Fcontent%2Fdefault_avatar-445fbbabfc8dc9188fb5967fe43322ee0c3e0dd1e10f378bf8343784af5a13eb.webp&r=pg)
Unsubscribed User
11,042 Pointstodo_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](https://secure.gravatar.com/avatar/88473f11a59731bf1bbeb19686145a65?s=96&d=https%3A%2F%2Fecs-static.teamtreehouse.com%2Fassets%2Fcontent%2Fdefault_avatar-445fbbabfc8dc9188fb5967fe43322ee0c3e0dd1e10f378bf8343784af5a13eb.webp&r=pg)
David O' Rojo
11,051 PointsThe 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.