简体   繁体   中英

Stub global cookies variable in Rspec Rails test

The Rspec test looks like this:

RSpec.describe Api::UsersController, type: :controller do
    describe 'POST #create' do
        subject { post :create, params: create_params }

        context '...' do

In the controller, I use:

cookies.permanent[:foo] == 'bar'

However, I'm getting:

NameError:
       undefined local variable or method `cookies' for #<Api::UsersController:0x000000137702f0>

Another SO question has an answer that says to add type: :request to describe , but this causes other errors. I'd rather just completely stub out cookies so cookies.permanent[:foo] == 'bar' is always false. How do I do that?

By default controllers in rails-api don't include the middleware that handles cookies. If you need cookies then you need to add that middleware:

config.middleware.use ActionDispatch::Cookies

For the above problem, you need to include

ActionController::Cookies

in your spec files

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM