kchak
kchak

Reputation: 8062

Why NoMethodError for instance method of another class in Rspec?

I have a Player class in player.rb

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

The board.move_valid? and other board methods are defined in the file for the 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

Both class files are in the lib folder.

On running rspec command from the project's root directory, I get the 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

The corresponding rspec test file contents are:

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

The project involves a main.rb file in a bin folder which requires both the class definitions, and works.

Upvotes: 0

Views: 46

Answers (1)

Sara Fuerst
Sara Fuerst

Reputation: 6068

This is occuring because of the order of the variables you are passing into make_move.

make_move takes in position followed by board. The error is stating that move_valid is is a string instead of an instance of Board.

This line should have the parameters swapped as shown:

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

Upvotes: 4

Related Questions