8

In my Dashboard#Index, I have this:

  def index        
    tagged_nodes = Node.includes(:user_tags).tagged_with(current_user.email)    
  end

How do I test this with RSpec?

I tried:

  expect(assigns(tagged_nodes)).to match Node.includes(:user_tags).tagged_with(u1.email)

But that gives me this error:

 NameError:
       undefined local variable or method `tagged_nodes' for #<RSpec::ExampleGroups::DashboardController::GETIndex:0x007fe4edd7f058>

2 Answers 2

10

You cannot (and should not) test local variables. However, you can and should test instance variables, which are the ones that start with @. For that you use the assigns helper, passing it the name of the instance variable as a symbol. If we want the value of the instance variable @tagged_nodes, we call assigns(:tagged_nodes) (note the :).

So if your controller method looks like this:

def index        
  @tagged_nodes = Node.includes(:user_tags).tagged_with(current_user.email)    
end

...you would access @tagged_nodes with assigns(:tagged_nodes):

expect(assigns(:tagged_nodes))
  .to match Node.includes(:user_tags).tagged_with(u1.email)
Sign up to request clarification or add additional context in comments.

2 Comments

Yeh....I know how to test instance variables. So should I have no local variables in my controller?
You can have local variables, but you don't need to test them. You should test the controller's outward behavior: given a certain request, what response it gives (or what data it passes to the view). Local variables are private state and in general you don't test private state.
-1

Try this code:

def index        
  tagged_nodes = Node.includes(:user_tags).tagged_with(current_user.email)    
end

you would access tagged_nodes with controller.tagged_nodes

expect(controller.tagged_nodes)
  .to match Node.includes(:user_tags).tagged_with(u1.email)

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.