2016-04-01 18 views
2

が、私は特に記事を作成するには、APIのRSpecのを実行しています。ここ 不正なリクエスト(エラーコード400)を修正する方法を教えてください。

は私の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

'post.valid?'が 'false'であることは明らかです。理由を明らかにする!おそらく 'p post.errors'をあなたのコントローラーメソッドの' else'部分に追加してください。 – spickermann

+0

log/test.logを調べて、エラーを確認できます。また、デバッグに役立つその他の質問にリンクすることもできます。 – Shishir

+0

@Shishirどうすればデバッグヘルプの質問にリンクすることができますか?ありがとう! – Iggy

答えて

1

@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 
関連する問題