为什么 Rspec 中另一个 class 的实例方法没有方法错误?

Why NoMethodError for instance method of another class in Rspec?

我在 player.rb

中有一个玩家 class
class Player
  attr_reader :name, :symbol
  ...
  def make_move?(position, board)
    if board.move_valid?(position)
        board.update(position, symbol)
        return true
    else
        return false
    end
  end 
  ...
end

board.move_valid? 和其他板方法在文件中定义为 Board class, board.rb

class Board
...
  def move_valid?(position)
    correct_pos = ("1".."9").include?(move)
    if correct_pos
      is_not_occupied = pos[move.to_i - 1].eql?(move)
    end
    correct_pos and is_not_occupied
  end

  def update(p, s)
  ...
  end
...
end

两个 class 文件都在 lib 文件夹中。

在项目根目录的 运行 rspec 命令上,我得到 error:

Player
  #make_move?
    marks a valid spot on the board (FAILED - 1)

Failures:

  1) Player#make_move? marks a valid spot on the board
     Failure/Error: if board.move_valid?(position)

     NoMethodError:
       undefined method `move_valid?' for "3":String
     # ./lib/player.rb:12:in `make_move?'
     # ./spec/player_spec.rb:9:in `block (3 levels) in <top (required)>'

Finished in 0.0032 seconds (files took 0.11769 seconds to load)
16 examples, 1 failure

Failed examples:

rspec ./spec/player_spec.rb:6 # Player#make_move? marks a valid spot on the board

对应的rspec测试文件内容为:

require './lib/player'
require './lib/board'

describe Player do
    describe "#make_move?" do
        it "marks a valid spot on the board" do
            player = Player.new("Abc", "X")
            board = Board.new
            expect(player.make_move?(board, "3")).to eql(true)
        end
    end
end

该项目涉及 bin 文件夹中的一个 main.rb 文件,该文件 require 是 class 定义,并且有效。

发生这种情况是因为您传递给 make_move 的变量的顺序。

make_move 接受 position,然后是 board。错误表明 move_valid 是一个字符串而不是 Board 的实例。

此行应按如下所示交换参数:

expect(player.make_move?("3", board)).to eql(true)