我在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?
类和其他董事会方法是在Board
类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
两个类文件都位于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
既可以定义类,也可以正常工作。
答案 0 :(得分:4)
发生这种情况是由于您要传递给make_move
的变量的顺序。
make_move
接受position
,后接board
。该错误表明move_valid
是一个字符串,而不是Board
的实例。
此行应按如下所示交换参数:
expect(player.make_move?("3", board)).to eql(true)