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

时间:2016-04-01 06:21:20

标签: ruby-on-rails ruby rspec http-status-code-400

我正在为api运行RSpec,专门用于创建帖子(我也在努力:更新和:destroy,但这两个运行正常。我遇到了麻烦:创建)

以下是我的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)>'

我真的不确定代码有什么问题。路线很好。如何通过测试?

1 个答案:

答案 0 :(得分:1)

要获得@spickermann提供的更好的解决方案,请在post操作中将@post更改为#create,并将以下代码添加到您的规范中并从那里开始工作。我打赌你必须在你的控制器中做@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