【问题标题】:Instance variable showing up as `nil` in rspec实例变量在 rspec 中显示为“nil”
【发布时间】:2016-02-17 15:33:14
【问题描述】:

我有以下测试代码:

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 methodgrid' 中为 nil:NilClass (NoMethodError)

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

我在这里的意图是将块对象分配给棋盘的网格实例变量(8x8数组)。

【问题讨论】:

    标签: ruby testing rspec


    【解决方案1】:

    尝试改用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
    

    【讨论】:

    • 这不能回答问题。
    • /.rvm/gems/ruby-2.2.1/gems/rspec-core-3.4.1/lib/rspec/core/example_group.rb:667:in method_missing': board` 不是可用于示例组(例如 describecontext 块)。它只能从单个示例(例如it 块)或在示例范围内运行的构造(例如beforelet 等)中获得。 (RSpec::Core::ExampleGroup::WrongScopeError)
    • 我认为您误用了 context 块 - 请参阅我的编辑
    • 一切都很好,但是前块中的@piece 为零。它没有提到任何东西。所以我的测试仍然无法正常工作。
    • 好,我会删除我的答案。
    猜你喜欢
    • 2020-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-07
    相关资源
    最近更新 更多