【问题标题】:Set request headers for Rspec and Rack::Test in Ruby on Rails在 Ruby on Rails 中为 Rspec 和 Rack::Test 设置请求标头
【发布时间】:2015-04-01 12:01:57
【问题描述】:

我目前正在尝试使用 Rspec 为我的应用程序测试登录和注销 JSON 端点。我正在使用 devise 和 devise_token_auth gems 来为我的身份验证构建 JSON 端点。

我可以成功登录用户,但是在注销时需要存在多个请求标头,以便注销功能找到正确的用户并完成。

我尝试将标头添加到我当前的 Rack 会话中,但它似乎 在创建请求时删除了它们。到目前为止,这是我的代码:

辅助方法(spec/support/api_helper.rb):

def login_user
        user = create(:user)
        post '/api/v1/auth/sign_in', email: user.email, password: user.password, format: :json
        return { 
                'token-type' => 'Bearer', 
                'uid' => last_response.headers['uid'], 
                'access-token' => last_response.headers['access-token'], 
                'client' => last_response.headers['client'], 
                'expiry' => last_response.headers['expiry'] 
            }
end

我的 Rspec 示例 (spec/api/v1/authentication_spec.rb):

describe 'DELETE /api/v1/auth/sign_out' do

        it 'should destroy your current session and log you out' do
            login_user
            delete '/api/v1/auth/sign_out', {}, login_user
            expect(last_response.status).to eq 200
            expect(parse_json(last_response.body['success'])).to eq true
        end
    end

尝试使用 DELETE HTTP 动词请求用户注销时的输出:

=> #<Rack::MockResponse:0x007fc0f66fa748 @original_headers={"X-Frame-Options"=>"SAMEORIGIN", "X-XSS-Protection"=>"1; mode=block", "X-Content-Type-Options"=>"nosniff", "Content-Type"=>"application/json; charset=utf-8", "Cache-Control"=>"no-cache", "X-Request-Id"=>"754c89bb-7a8f-4c83-b32b-dc9ed3404863", "X-Runtime"=>"0.010023"}, @errors="", @body_string=nil, @status=401, @header={"X-Frame-Options"=>"SAMEORIGIN", "X-XSS-Protection"=>"1; mode=block", "X-Content-Type-Options"=>"nosniff", "Content-Type"=>"application/json; charset=utf-8", "Cache-Control"=>"no-cache", "X-Request-Id"=>"754c89bb-7a8f-4c83-b32b-dc9ed3404863", "X-Runtime"=>"0.010023", "Content-Length"=>"37"}, @chunked=false, @writer=#<Proc:0x007fc0f66fa338@/Users/tomdallimore/.rbenv/versions/2.1.3/lib/ruby/gems/2.1.0/gems/rack-1.6.0/lib/rack/response.rb:30 (lambda)>, @block=nil, @length=37, @body=["{\"errors\":[\"Authorized users only.\"]}"]>

我还尝试向当前 Rack 会话添加标题,如下所示:

header 'uid', login_user['uid']
header 'token-type', 'Bearer'
header 'access-token', login_user['access-token']
header 'client', login_user['client']
header 'expiry', login_user['expiry']

有谁知道为什么在发出新请求时会从 Rack 会话中删除标头?我还能如何向 Rack 会话添加标头?

【问题讨论】:

    标签: ruby-on-rails json rspec devise rack


    【解决方案1】:

    我认为你正在做的事情应该有效。此外,您可以设置标题 header('name', 'value').

    无论如何,你应该检查

    post '/api/v1/auth/sign_in', email: user.email, password: user.password, format: :json
    

    user.password 应该经过哈希处理,因此如果您这样发送,您将无法登录。

    【讨论】:

    • 我找了几个小时header('name', 'value')。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-19
    • 1970-01-01
    • 1970-01-01
    • 2012-03-28
    • 1970-01-01
    • 2015-12-12
    • 1970-01-01
    相关资源
    最近更新 更多