RSpec test for update in another action


I am building an application in Rails 5 that sends user inputs back to a controller called "TestsController." If the params[:answer] matches the "correct_answer" in the controller action, the "test" object, which the TestsController controls, will have it's "score" increased by 1. If the answer does not match, the score is not increased.

Here is that action:

def question1
    @test = Test.find(params[:id])
    correct_answer = "<p>"
    user_answer = params[:answer]
    if user_answer == correct_answer[:success] = "That is correct!"
        new_score = @test.score += 1
        @test.update(score: new_score)
    elsif params[:answer].present? && params[:answer] != correct_answer[:danger] = "Wrong answer."

Here is the RSpec test I attempted to write for this controller action:

describe 'GET #question1' do 

    it 'updates score if params match answer' do
        get :question1, params: { id:, answer: '<p>'}
        expect(test1.score).to eq(1)


This test throws this error:

1) TestsController GET #question1 updates score if params match answer
 Failure/Error: new_score = @test.score += 1

   undefined method `+' for nil:NilClass

I am unsure what I am doing wrong. It seems the @test object is not being assigned... although I wrote another test in this same RSpec file that says it IS being assigned. Plus this works in the app, just not in the test. Can someone help?

Actually it is telling you that test.score is nil.

You could solve it in two ways:

  • When creating a test instace set its score to 0 with a before_create callback
  • In the controller after @test = Test.find(params[:id]): @test.score = 0 if @test.score.nil?

PS: I would add a validation to ensure score is an integer