AlterEchoes
AlterEchoes

Reputation: 31

Getting nilClass error while testing with rspec

I'm testing my project with rspec and now I'm up to the controllers part. I'm testing this method:

def accept
  @app = App.find(params[:id])
  @invite = Invite.find_by(app: @app.name, receiver: current_dev.id)
  @dev = Developer.find(@invite.sender)
  @app.developers << @dev
  respond_to do |format|
    if @invite.destroy
      format.html { redirect_to @app, notice: 'A new developer joined your team!' }
      format.json { render :show, status: :destroyed, location: @app }
    else
      format.html { render :back }
      format.json { render json: @invite.errors, status: :unprocessable_entity }
    end
  end
end

and this is the test part:

it "should accept an invite (1)" do
  invite = Invite.create(:app => "test", :sender => "2", :receiver => "1")
  get :accept, :id => 1
  assert_response :success
end

but when I run the rspec command I get this error:

InvitesController should accept an invite (1)
Failure/Error: @dev = Developer.find(@invite.sender)

NoMethodError:
  undefined method `sender' for nil:NilClass

So I am assuming that the invite object is nil but I can't figure out why this happens. I test the function via browser and everything works fine. This is also causing same errors in different controller methods, every time just because my invite object is nil. Why is this happening?

Upvotes: 2

Views: 551

Answers (1)

AlterEchoes
AlterEchoes

Reputation: 31

SOLVED:

  • Main reason things weren't working: mismatch between created invite parameters and current parameters (app, current_developer)
  • Debug: setting breakpoints/printing values of what was needed in the controller and what was needed in the model.
  • Fixing: created objects that were missing in order to match parameters; correct solution was


it "should accept an invite (1)" do
  invite = Invite.create(:app => @app.name, :sender => "2", :receiver => @developer.id)
  get :accept, :id => @app.id
  assert_response :redirect
end

Upvotes: 1

Related Questions