Ich habe ein Problem beim Versuch, eine meiner POST-API-Aufrufe zu testen, die einen neuen Benutzer erstellt:Wie man richtig eine ‚Post‘ testen (create) Methode in Ruby on Rails mit Weintraube und MongoDB
class API::V1::Users::APITest < ActiveSupport::TestCase
include Rack::Test::Methods
def app
Rails.application
end
test 'POST /api/v1/users can create a user' do
post "/api/v1/users", params: { username: "new_user", email: "[email protected]",
first_name: "first", last_name: "last" },
assert last_response.ok?, "#{last_response.inspect}"
end
end
Es gibt eine Antwort sagen, dass die 'username' Parameter, 'E-Mail', 'first_name' und 'last_name' fehlen:
#<Rack::MockResponse:0x007ffc34108b40 @original_headers={"Content-Type"=>"application/json", "Content-Length"=>"94", "Cache-Control"=>"no-cache", "X-Request-Id"=>"8a5b0a14-522c-4407-830c-28dc6402f52c", "X-Runtime"=>"0.009955", "Vary"=>"Origin"}, @errors="", @status=400, @header={"Content-Type"=>"application/json", "Content-Length"=>"94", "Cache-Control"=>"no-cache", "X-Request-Id"=>"8a5b0a14-522c-4407-830c-28dc6402f52c", "X-Runtime"=>"0.009955", "Vary"=>"Origin"}, @writer=#<Proc:[email protected]/[FOLDERS]/vendor/bundle/gems/rack-2.0.1/lib/rack/response.rb:32 (lambda)>, @block=nil, @length=94, @body=["{\"error\":\"username is missing, email is missing, first_name is missing, last_name is missing\"}"]>
MongoDB Benutzermodell
class User
include Mongoid::Document
field :username, type: String
field :email, type: String
field :first_name, type: String
field :last_name, type: String
field :picture, type: String
field :video, type: String
field :twitter, type: String
field :phone, type: String
end
Aber ich glaube, ich Setup die POST-Methode richtig haben, denn wenn ich es in der Traube Swagger UI laufen, es läuft erfolgreich:
Defaults
module API
module V1
module Defaults
extend ActiveSupport::Concern
included do
prefix "api"
version "v1", using: :path
default_format :json
format :json
helpers do
def permitted_params
@permitted_params ||= declared(params, include_missing: false)
end
def logger
Rails.logger
end
end
end
end
end
end
API
module API
module V1
class Users < Grape::API
include API::V1::Defaults
resource :users do
desc 'Create a user'
params do
requires :username, type: String, desc: 'Unique username'
requires :email, type: String, desc: 'Email'
requires :first_name, type: String, desc: 'First name'
requires :last_name, type: String, desc: 'Last name'
end
post do
User.create!({
username: params[:username],
email: params[:email],
first_name: params[:first_name],
last_name: params[:last_name]
})
end
end
end
end
end
Successful Swagger UI POST call
Was mache ich falsch? Ist meine Syntax korrekt?
danke! es funktionierte! –