Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I test a local variable inside a controller with Rspec?

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>
like image 941
marcamillion Avatar asked May 04 '15 21:05

marcamillion


People also ask

How do I run a specific test in RSpec?

To run a single Rspec test file, you can do: rspec spec/models/your_spec. rb to run the tests in the your_spec. rb file.

How do I declare a variable in RSpec?

Another way to define a variable in RSpec is to use the let syntax. The let method should be called inside an example group. The first argument is the name of a variable to define.

How do I test a controller in Ruby on Rails?

The currently accepted way to test rails controllers is by sending http requests to your application and writing assertions about the response. Rails has ActionDispatch::IntegrationTest which provides integration tests for Minitest which is the Ruby standard library testing framework.

Is RSpec used for unit testing?

RSpec is a unit test framework for the Ruby programming language. RSpec is different than traditional xUnit frameworks like JUnit because RSpec is a Behavior driven development tool. What this means is that, tests written in RSpec focus on the "behavior" of an application being tested.


1 Answers

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)
like image 99
Jordan Running Avatar answered Oct 09 '22 19:10

Jordan Running