Reputation: 4617
This following Controller test is failing, and I can't figure out why:
describe "GET 'index'" do
before(:each) do
@outings = FactoryGirl.create_list(:outing, 30)
@user = FactoryGirl.create(:user)
end
it "should be successful" do
get :index
response.should be_success
end
end
Rspec offers up the (rather unhelpful) error:
Failure/Error: response.should be_success
expected success? to return true, got false
Here's the code for the actual Controller, too:
def index
if @user
@outings = Outing.where(:user_id => @user.id)
@outing_invites = OutingGuest.where(:user_id => @user.id)
else
flash[:warning] = "You must log in to view your Outings!"
redirect_to root_path
end
end
Anyone have an idea what's causing my test to fail? I assume it may have something to do with the conditional in the Outing Controller, but I have no idea what a passing test would look like...
Upvotes: 1
Views: 115
Reputation: 23226
You're confusing instance variables between two separate classes - the controller is its own class and the specification is its own class. They don't share state. You could try this simple example to get a better understanding...
def index
// obvious bad code, but used to prove a point
@user = User.first
if @user
@outings = Outing.where(:user_id => @user.id)
@outing_invites = OutingGuest.where(:user_id => @user.id)
else
flash[:warning] = "You must log in to view your Outings!"
redirect_to root_path
end
end
I'll guess that FactoryGirl.create_list(:outing, 30)
doesn't create an outing associating the first user with the outing since you're creating the user after you create the outing so your Outing.where
will fail as well.
Its important to understand that when you are including the database in your test stack the database needs to contain the data in the way the test expects. So if your controller is querying for outings belonging to a specific user your spec needs to setup the environment such that the user the controller will retrieve (in this case, the terrible line with User.first
from my example) will also have the outings associated with it that the specification is expecting.
Upvotes: 1