Iggy
Iggy

Reputation: 5251

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

I am running RSpec for api, specifically to create posts (I am also working on :update and :destroy, but those two are running fine. I am having trouble with :create)

Here are my 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

And here is my create

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

Here is the error code that I keep getting:

.........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)>'

I am really not sure what is wrong with the code. The routes work fine. How can I make the tests pass?

Upvotes: 2

Views: 1863

Answers (1)

Thomas R. Koll
Thomas R. Koll

Reputation: 3139

For a better solution tha @spickermann suggested, change post to @post in your #create action and add the code below to your specs and work from there. I bet you have to do something like @post.user = current_user in your controller.

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

Upvotes: 1

Related Questions