Home > front end >  Is there any way to give logged in condition in rspec? (Ruby on Rails)
Is there any way to give logged in condition in rspec? (Ruby on Rails)

Time:08-31

my rspec file ->

  describe 'GET /users' do
    it 'test user list page' do
      get '/users'
      expect(response).to have_http_status(:success)
    end
  end

I maked login in my app, but I don't know how to define 'login' with 'before' in rspec file. my login is using session, and I don't have to use specific user. how can I check user logged in on rspec request test? I want to test logged in user can access to /users url in rspec file

CodePudding user response:

you can do it by mocking. The details depend on how your login status is determined, but suppose your application controller has a before_action like this:

# application_controller.rb

before_action :verify_login

# typically the checking is delegated
def verify_login
  Authorize.logged_in?(current_user, session)
end

Where the checking is executed in the Authorize service model.

Now in Rspec you just have to mock the response:

before do
  current_user = FactoryBot.create(:user)
  session = Session.create
  expect(Authorize).to receive(:logged_in?).with(current_user, session).and_return(true)
end

it "should respond to logged-in user" do
  get '/users'
  expect(response).to have_http_status(:success)(
end
  • Related