
Unsubscribed User
11,041 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,050 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.