Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to mock a current_user in rspec? #16

Open
gamesover opened this issue Mar 15, 2018 · 5 comments
Open

How to mock a current_user in rspec? #16

gamesover opened this issue Mar 15, 2018 · 5 comments

Comments

@gamesover
Copy link

gamesover commented Mar 15, 2018

If in keynote presenter, current_user is included.

def method(user)
  if user == current_user
  ...
end

In rspec, I don't know how to mock this current_user variable.

allow(presenter).to receive(:current_user).and_return(user) does not work and rspec said presenter is not defined.

Could you please show me an example?

Thanks.

@Spaceghost
Copy link

If you look at the helper you'd see that you could provide the presenter instance yourself.

What sort of test are you writing? For what object, in what context, and what is the goal of the test?

@gamesover
Copy link
Author

@Spaceghost , if you look at my example method. There is a variable current_user from controller helper. How can I assign current_user a value when running rspec?

@Spaceghost
Copy link

Spaceghost commented Mar 21, 2018 via email

@gamesover
Copy link
Author

Given a TestPresenter

class TestPresenter < Keynote::Presenter
  presents :test

  def get_current_user
    current_user 
  end
end

Please be noted, the current_user is defined in application_controller.rb, to use it in presenter is not issue. But how to test in rspec?

# frozen_string_literal: true

RSpec.describe TestPresenter do
  subject { k(test) }
  let(:test) { create(:test) }

  describe '#get_current_user' do
    it 'returns current_user' do
      expect(subject.get_current_user).to eq(user)
    end
  end
end

If you run the above rspec directly, it prompts error
NameError: undefined local variable or method current_user' for`

@Spaceghost
Copy link

Spaceghost commented Aug 20, 2018 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants