Rails 如何修复格式错误的请求(错误代码 400)?

Rails how to fix malformed request (error code 400)?

我是 运行 RSpec api,专门负责创建帖子(我也在研究 :update 和 :destroy,但这两个 运行 很好. 我遇到了问题 :create)

这是我的 RSpec:

describe "POST create" do
   before { post :create, topic_id: my_topic.id, post: {title: @new_post.title, body: @new_post.body} }

   it "returns http success" do
     expect(response).to have_http_status(:success)
   end

   it "returns json content type" do
     expect(response.content_type).to eq 'application/json'
   end

   it "creates a topic with the correct attributes" do
     hashed_json = JSON.parse(response.body)
     expect(hashed_json["title"]).to eq(@new_post.title)
     expect(hashed_json["body"]).to eq(@new_post.body)
   end
 end

这是我的作品

def create
    post = Post.new(post_params)

    if post.valid?
      post.save!
      render json: post.to_json, status: 201
    else
      render json: {error: "Post is invalid", status: 400}, status: 400
    end
  end

这是我不断收到的错误代码:

.........F.F....

Failures:

  1) Api::V1::PostsController authenticated and authorized users POST create returns http success
     Failure/Error: expect(response).to have_http_status(:success)
       expected the response to have a success status code (2xx) but it was 400
     # ./spec/api/v1/controllers/posts_controller_spec.rb:78:in `block (4 levels) in <top (required)>'

我真的不确定代码有什么问题。路线工作正常。我怎样才能让测试通过?

为了获得 @spickermann 建议的更好的解决方案,请在您的 #create 操作中将 post 更改为 @post 并将下面的代码添加到您的规范中并从那里开始工作。我打赌你必须在你的控制器中做类似 @post.user = current_user 的事情。

it "@post is valid and have no errors" do
  expect(assigns[:post]).to be_valid
  expect(assigns[:post].errors).to be_empty
end