2

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?

Iggy
  • 5,129
  • 12
  • 53
  • 87
  • 1
    It is obvious that `post.valid?` is `false`. Find out why! Perhaps by adding a `p post.errors` into the `else` part of your controller method. – spickermann Apr 01 '16 at 06:45
  • You can inspect log/test.log to see the error. Alternately, you can link in your question for other to help you debug. – Shishir Apr 01 '16 at 06:46
  • @Shishir do you mind sharing how I can link the question for debugging help? Thanks! – Iggy Apr 01 '16 at 06:49
  • I meant link to copy of log/test.log. You can use pastebin, gist or any such sharing tool. – Shishir Apr 01 '16 at 06:51

1 Answers1

1

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
Thomas R. Koll
  • 3,131
  • 1
  • 19
  • 26