Rspec Controller tests, passing JSON params

試著忘記壹切 提交于 2019-12-06 00:39:33

问题


I'm trying to achieve the following: create a POST json request within RSpec Controller test, passing it params. Here's my code

it 'returns access_token' do
    post :login, email: 'bla', password: 'bla1', format: :json
end

What I get in controllers request.body.read is a string with params, but passed like this email=bla&password=bla1

This is definitely not a JSON. But, if I make request using CURL

curl -d '{"email": "bla@bla.com" }' http://127.0.0.1:3000/users/login --header "Accept: application/json" --header "Content-Type: application/json"

I get my request.body.read as a correct json

"{\"email\": \"bla@bla.com\", \"password\": \"bla1\" }"

So how do I pass it this way from my rspec?


回答1:


post "/models/#{@model.id}",
        params: {
            some_field: "1234",
        },
        as: :json



回答2:


You can pass header in your RSpec file.

header "Content-Type", "application/json"
post :something

And you can pass params like this :

post :create, :object => { :email => email,
                           ...
                         }


来源:https://stackoverflow.com/questions/29016140/rspec-controller-tests-passing-json-params

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!