super_noobling
super_noobling

Reputation: 323

Instance variable showing up as `nil` in rspec

I have the following test code:

require_relative '../spec_helper'

describe Chess::King do
  before do
    @piece = Chess::King.new('king1',:black)
    @board = Chess::Board.new
  end

  describe '#possible_moves' do
    context "placing king at location 4,5" do
      @board.grid[4][5] = @piece
      subject {@piece.possible_moves(@board)}
      it {is_expected.to eq([3,5],[3,6],[4,6],[5,6],[5,5])}
    end
  end
end

Why am I getting this error:

in block (3 levels) in <top (required)>': undefined methodgrid' for nil:NilClass (NoMethodError)

I am not sure about this line: @board.grid[4][5] = @piece.

My intention here is to assign the piece object to the grid instance variable of board (8x8 array).

Upvotes: 1

Views: 303

Answers (1)

Uri Agassi
Uri Agassi

Reputation: 37409

Try using let instead:

require_relative '../spec_helper'

describe Chess::King do
  let(:piece) { Chess::King.new('king1',:black) }
  let(:board) { Chess::Board.new }

  describe '#possible_moves' do
    context "placing king at location 4,5" do
      before(:each) { board.grid[4][5] = piece }
      subject {piece.possible_moves(board)}
      it {is_expected.to eq([3,5],[3,6],[4,6],[5,6],[5,5])}
    end
  end
end

Upvotes: 0

Related Questions