【问题标题】:Rspec Controller tests, passing JSON paramsRspec 控制器测试,传递 JSON 参数
【发布时间】:2015-03-12 17:13:07
【问题描述】:

我正在尝试实现以下目标:在 RSpec Controller 测试中创建一个 POST json 请求,并传递它的参数。这是我的代码

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

我在控制器 request.body.read 中得到的是一个带参数的字符串,但像这样传递 email=bla&password=bla1

这绝对不是 JSON。但是,如果我使用 CURL 提出请求

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

我的 request.body.read 是正确的 json

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

那么我如何从我的 rspec 中以这种方式传递它?

【问题讨论】:

    标签: ruby-on-rails json testing rspec controller


    【解决方案1】:
    post "/models/#{@model.id}",
            params: {
                some_field: "1234",
            },
            as: :json
    

    【讨论】:

      【解决方案2】:

      您可以在 RSpec 文件中传递标头。

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

      你可以像这样传递参数:

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

      【讨论】:

      • 您好,感谢您的回复。其实是一样的,因为 format: :json 设置了所有的头文件。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-28
      相关资源
      最近更新 更多