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 trialUnsubscribed 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
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.