我正在使用 Rack::Test测试我的应用程序并需要测试通过 AJAX 发布的数据。
我的测试看起来像:
describe 'POST /user/' do
include Rack::Test::Methods
it 'must allow user registration with valid information' do
post '/user', {
username: 'test_reg',
password: 'test_pass',
email: 'test@testreg.co'
}.to_json, {"CONTENT_TYPE" => 'application/json', "HTTP_X_REQUESTED_WITH" => "XMLHttpRequest"}
last_response.must_be :ok?
last_response.body.must_match 'test_reg has been saved'
end
end
但是在服务器端它没有接收到 POSTed 数据。
我也试过在没有 to_json
的情况下只传递参数哈希,但这没有任何区别。
知道怎么做吗?
最佳答案
您的发布端点必须解析发布的 JSON 正文本身,我假设您已经这样做了。你能发布你的端点是如何工作的,还有机架测试、机架、ruby 和 sinatra 版本号吗?另请提及您如何测试服务器是否收到任何东西——即测试模型可能会混淆您的检测。
post '/user' do
json_data = JSON.parse(request.body.read.to_s)
# or # json_data = JSON.parse(request.env["rack.input"].read)
...
end
关于ajax - 使用 Rack::Test 测试 AJAX POST - 如何传递数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18713714/