Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Rails如何修复格式错误的请求(错误代码400)?_Ruby On Rails_Ruby_Rspec_Http Status Code 400 - Fatal编程技术网

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

Ruby on rails Rails如何修复格式错误的请求(错误代码400)?,ruby-on-rails,ruby,rspec,http-status-code-400,Ruby On Rails,Ruby,Rspec,Http Status Code 400,我正在运行rspecforapi,专门用于创建帖子(我也在处理:update和:destroy,但这两个都运行得很好。我在:create方面遇到了问题) 以下是我的简历: 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

我正在运行rspecforapi,专门用于创建帖子(我也在处理:update和:destroy,但这两个都运行得很好。我在:create方面遇到了问题)

以下是我的简历:

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)>'
……F.F。。。。
失败:
1) Api::V1::PostsController身份验证和授权用户POST create返回http成功
失败/错误:期望(响应)。具有\u http\u状态(:成功)
预期响应具有成功状态代码(2xx),但为400
#./spec/api/v1/controllers/posts\u controller\u spec.rb:78:in“block(4级)in”

我真的不确定代码出了什么问题。这些路线运作良好。我怎样才能通过考试

要获得@spickermann建议的更好的解决方案,请在
#创建
操作中将
post
更改为
@post
,并将下面的代码添加到您的规范中,然后从那里开始工作。我打赌您必须在控制器中执行类似于
@post.user=current\u user
的操作

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

很明显,
post.valid?
false
。找出原因!也许可以通过在控制器方法的
else
部分添加
p post.errors
来实现。您可以检查log/test.log以查看错误。或者,您可以将您的问题链接到其他人以帮助您调试。@Shishir您介意分享我如何将问题链接到调试帮助吗?谢谢我的意思是链接到log/test.log的副本。您可以使用pastebin、gist或任何此类共享工具。