mardi 15 octobre 2019

How do I test an instance variable in a controller?

A couple of my mentors have told me to test a piece of code with controller spec even though the contents are being tested by some request specs. I am wondering if I can test whether an instance variable like @user can be set to someObject or nil from within an rspec controller test?

I've tried a couple different ways to test this so far, but my skills regarding rspec testing are to say the least, elementary. The first thing I tried was mocking out the current_user and the 'User.get_from_auth_user(current_user). The mocked object prints fine and outputs. The problem is... I want to be able to say something like expect(@user).to equal(mockedUser) but this never seems to work. I always get something like:

Expect does not equal received
expected is nil
received is { someMockedObject }

Here is the code I want to test.

class ApplicationController < ActionController::Base
  before_action :set_user

  def set_user
    return if current_user.nil?

    @user = User.get_from_auth_user(current_user)
  end
end

I want to know if I'm going down the right path or what would be the better alternative to fully test this chunk of code. I feel like the answer should be a simple one.

Aucun commentaire:

Enregistrer un commentaire