How can I achieve same result using allow(controller) in request type?

21 views
Skip to first unread message

Fernando Iwamoto

unread,
Sep 6, 2021, 4:25:05 PM9/6/21
to rspec
I have my test controller using this type:

describe CompanyController, type: :controller do

which allow me to skip authentication:

before do
allow(controller).to receive(:authenticate_client).and_return(true)
allow(controller).to receive(:current_client).and_return(client)
end

How can I achieve using the same as above, but for request type?

before do
allow(controller).to receive(:authenticate_client).and_return(true)
allow(controller).to receive(:current_client).and_return(client)
end

Joseph Haig

unread,
Sep 6, 2021, 4:55:13 PM9/6/21
to rs...@googlegroups.com
When running a request spec test that requires authentication you will need to have the web clients session set up accordingly, which would involve making the necessary requests to log in. Eg, you could have something like,

before do
  post('/login', params: { client_id: client.id, password: 'test-password' })
end

However, if you are using the devise gem for authentication there is a helper you can use to do the signing in for your. See https://github.com/heartcombo/devise/wiki/How-To:-sign-in-and-out-a-user-in-Request-type-specs-(specs-tagged-with-type:-:request)

So you might have something like this,

before do
  sign_in client
end

Incidentally, for controller specs you can add `session: { client_id: client.id }` (for example) to the get and post requests in your tests to do the same without having to stub the authentication methods. See https://stackoverflow.com/questions/22451969/rspec-set-session-object

Hope this helps. The code examples may not be exactly correct as I am typing them in mostly from memory, with the aid of Google.

Regards,

Joe

--
You received this message because you are subscribed to the Google Groups "rspec" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rspec+un...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rspec/fbe7b1ae-7e75-47eb-a718-41d48bf5a9ban%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages