(LikesController#create)预期#count已更改为1,但已更改为0,请教我一个提示

时间:2018-12-28 03:21:59

标签: ruby-on-rails ruby rspec

我更大。 我研究了Rspec。

我做了一个实现,使我能够在自己的帖子上做得很好。

但是在浏览器上我执行了预期的动作,但是测试未通过。

destroy动作通过了测试,但是create动作没有通过测试。

我的错误是

Failure/Error: expect { post :create, format: :js, params: { post_id: post1.id, id: like.id } }.to change(Like, :count).by(1)
       expected #count to have changed by 1, but was changed by 0

我的代码是

require 'rails_helper'

RSpec.describe LikesController, type: :controller do
  let!(:user) { create(:user) }
  let!(:post1) { create(:post, user: user) }
  let!(:like) { create(:like, user_id: user.id, post_id: post1.id) }

  describe "#create" do
    before do
      sign_in user
    end

    it "response Ajex" do
      post :create, format: :js, params: { post_id: post1.id, id: like.id }
      expect(response.content_type).to eq 'text/javascript'
    end

    it "success like function" do
      expect { post :create, format: :js, params: { post_id: post1.id, id: like.id } }.to change(Like, :count).by(1)
    end
  end

  describe "#destroy" do
    before do
      sign_in user
    end

    it "response Ajex" do
      delete :destroy, format: :js, params: { post_id: post1.id, user_id: user.id, id: like.id }
      expect(response.content_type).to eq 'text/javascript'
    end

    it "delete like function" do
      expect { delete :destroy, format: :js, params: { post_id: post1.id, user_id: user.id, id: like.id } }.to change(Like, :count).by(-1)
    end
  end
end

likes_controller.rb

 class LikesController < ApplicationController
  def create
    @like =
current_user.likes.find_or_create_by(post_id:params[:post_id])
    @likes = Like.where(post_id: params[:post_id])
    @post = Post.find(params[:post_id])
  end

  def destroy
    like = current_user.likes.find_by(post_id: params[:post_id])
    like.destroy
    @likes = Like.where(post_id: params[:post_id])
    @post = Post.find(params[:post_id])
  end
end

我不能解决这个问题。 请教我一个提示。

1 个答案:

答案 0 :(得分:1)

您的代码在某处出现错误的可能性最大,这就是Like计数无法递增的原因。首先,我将尝试弄清楚为什么它没有增加。由于您一直在寻求提示,因此可以通过以下一种方式拆分“类似于函数的成功”块:

context "valid" do
  before do
    post :create, format: :js, params: { post_id: post1.id, id: like.id }
  end

  it "success" do
    # You can inject a binding.pry here if needed
    expect(response.status).to eq(200)
  end

  it "response" do
    # You can inject a `binding.pry` here if needed
    # You can also inspect the `response.body` with puts if needed
    expect(JSON.parse(response.body)).to include(
      # You would modify this to match the shape of your response
      post: a_hash_including(
        like: like.id
      )
    )
  end
end

您将要安装pry-railspry-byebug宝石(用于检查)。

将它们拆分后的原因是,它可以更轻松地确定问题(例如,您可以具有有效的响应代码,但没有预期的结果)。附带一些警告(会降低测试速度),但在此示例中,它将使您更容易确定post失败的原因。

上面的代码段应该可以帮助您调试错误;修复后,您可以恢复到以前的检查方法。