Question

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

Was it helpful?

Solution 2

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top