实例变量在rspec中显示为“nil”

时间:2016-02-17 06:42:49

标签: ruby testing rspec

我有以下测试代码:

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

为什么我收到此错误:

  

block (3 levels) in <top (required)>': undefined method网格&#39; for nil:NilClass(NoMethodError)

我不确定这一行:@board.grid[4][5] = @piece

我的目的是将棋子对象分配给棋盘的网格实例变量(8x8数组)。

1 个答案:

答案 0 :(得分:0)

请尝试使用let

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