销毁动作测试用例 rspec

Destroy action test cases rspec

m 是 rails 和 rspec 的新手 我有一个带有销毁动作的控制器

  before_action :authorize_user, only: %i[edit update destroy]

  def destroy
    @question.destroy
    respond_to do |format|
      format.html { redirect_to questions_url, notice: 'Question was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

我有一个私有方法

  def authorize_user
    redirect_to root_path if @question.user_id != current_user.id
  end

这是我写的rspec测试用例

  describe "DELETE /destroy" do
    context 'When user has signed in ' do
      let!(:user) { create(:user) }
      before do
        sign_in(user)
        
      end
      context 'User who created the question can destroy' do
        it "destroys the requested question" do
        
          expect {
            question = create(:question, user: user)
            # question.user = user
            # delete :destroy
            delete question_url(question)
          }.to change(Question, :count).by(-1)
        end
      end    
    end
  end

我收到这样的错误

expected `Question.count` to have changed by -1, but was changed by 0

你不能在 expect 块中创建你的问题,因为那样你总共得到 0 计数更改(0 在你创建之前,+1 用于创建,-1 用于您的销毁操作)。如果您将该行移到 expect 块之外,我怀疑您的测试会通过。

  question = create(:question, user: user)
  expect { delete question_url(question) }.to change(Question, :count).by(-1)