J Seabolt J Seabolt -4 years ago 59
Ruby Question

RSpec test for update within 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
flash.now[:success] = "That is correct!"
new_score = @test.score += 1
@test.update(score: new_score)
elsif params[:answer].present? && params[:answer] != correct_answer
flash.now[: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: test1.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?

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download