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
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)