Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
977 views
in Technique[技术] by (71.8m points)

ruby on rails - Destroy action test cases rspec

m new to rails and rspec I have a controller with destroy action

  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

I have a private method

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

This is the rspec test case I have written

  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

I am getting error like this

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can't create your question in the expect block, because then you get a total of 0 count changes (0 before you create, +1 for the create, -1 for your destroy action). If you move that line outside the expect block, I suspect your test will pass.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...