lundi 29 août 2016

Mock out a hash in Rails/Rspec

I need to mock a hash that is automatically given to my controller. I am currently trying to write Rspec tests for my application controller. It needs to get user information from an in-house gem (so I haven't been able to use any solutions I have seen in mocking session hashses) and populate our user fields with them.

  # Create and store the user if they have never logged in before, set user if they have an existing record
  def logged_in_user
    @logged_in_user ||= User.find_by(id: current_user['id']) || create_user
  end

  def create_user
    User.create(name: current_user['name'], email: current_user['email'], id: current_user['id'])
  end

current_user is a hash that is supplied by our in house log-in gem, the only thing I have added to the code in order to get it is "mount ...." in routes.rb (it is not retrieved/called for anyhwere else in my controller, this is the only place it is used). I know my code works because I can log in to the page and see that my user info is saved, but I need to write Rspec tests that cover all the methods. I have tried defining a hash named "current_user" and I still get an error telling me that '[]' is an undefined method on class:NilClass. I have tried using the allow(method).to receive(current_user) but when I do this our code coverage tool tells me that the inside of the create user statement was never reached

Aucun commentaire:

Enregistrer un commentaire