为什么在Rspec中另一个类的实例方法为NoMethodError?

时间:2019-06-21 11:37:41

标签: ruby rspec

我在player.rb中有一个Player类。

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?类和其他董事会方法是在Boardboard.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

两个类文件都位于lib文件夹中。

从项目的根目录运行rspec命令时,出现错误

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

该项目涉及一个main.rb文件夹中的bin文件,该文件require既可以定义类,也可以正常工作。

1 个答案:

答案 0 :(得分:4)

发生这种情况是由于您要传递给make_move的变量的顺序。

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

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

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