ruby Rspec失败/错误,预期内容类型为“json”,但获得了“text/html”

lb3vh1jj  于 2023-03-17  发布在  Ruby
关注(0)|答案(2)|浏览(148)

当我运行我的rspec测试时,我当前收到以下错误

Failure/Error: expect(last_response.header['Content-Type']).to eq('application/json')
     
       expected: "application/json"
            got: "text/html"
     
       (compared using ==)

我在这里的方法中指定了内容类型

get '/restart/?' do
        content_type :json
        # token authentication
        need_token!
        # restart operation
        exit_process
        status 200
        JSON.pretty_generate({ 'ok' => true, 'message' => 'Restarting ...' })
      end

当我运行curl get命令时,我得到了以下内容类型:应用程序/json

curl -X GET -H X-AUTH-TOKEN:$TOKEN --url localhost:8080/restart -I
HTTP/1.1 200 OK
Content-Type: application/json
X-Content-Type-Options: nosniff
Vary: Accept-Encoding
Content-Length: 85

为什么rspec测试返回“text/hmtl”?

2o7dmzc5

2o7dmzc51#

只需简单地将标头放入request中

request.headers['Content-Type'] = "application/json"

也可根据要求修改

xmjla07d

xmjla07d2#

你好!
我最近做了一个类似的测试!我可以看到你定义(sinatra)路由的方法有一点不同。我已经使用头指定了内容类型,它看起来像这样:

headers['Content-Type'] = 'application/pdf'

然后在我的测试中(我使用RSpec),我这样做:

expect(last_response.headers['Content-Type']).to eq('application/pdf')

相关问题