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>
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.
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With