0

I have a view spec where I'm testing conditional output. How do I get the spec to return the user I've mocked out?

View file:

.content
 - if @current_user.is_welcome == true
  Welcome to the site 

View spec:

before(:each) do 
  @user = mock_model(User)
  @user.stub!(:is_welcome).and_return(true)
  view.stub(:current_user).and_return(@user) 
end

it "show content" do 
  #assign(:current_user, stub_model(User, dismiss_intro: true))
  render
  rendered.should have_content("Welcome to the site")
end

Running the spec returns undefined method is_welcome for nil:NilClass

2 Answers 2

1

You have stubbed the method named current_user, not the instance variable @current_user.

view.stub(:current_user).and_return(@user)

That means, in the view, you should be using:

.content
 - if current_user.is_welcome == true
  Welcome to the site

Notice that it calls the method current_user instead of getting the @current_user instance variable.

If you need an instance variable, it is recommended that you have create a method current_user, which gets the instance variable and returns it.

3
  • My ApplicationController returns the instance variable helper_method :current_user which returns @current_user. I just don't think I'm understanding stubbing.
    – Simpleton
    Sep 8, 2012 at 9:22
  • you have stubbed a method, but you are trying to access a variable. The variable is nil because it hasn't been initialized.
    – ronalchn
    Sep 8, 2012 at 9:26
  • you shouldn't/can't. That's why I say to change your view.
    – ronalchn
    Sep 8, 2012 at 9:36
1

I ended up doing this which let me keep the @current_user variable in my view and made the spec pass:

before :each do
  @user = stub_model(User, is_welcome: true)
  assign(:current_user, @user)
end

Then to test the conditionality, just ran another spec in a context with a different before block:

before :each do
  @user = stub_model(User, is_welcome: false)
  assign(:current_user, @user)
end

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.