0

我试图在下面使用而不是从 Rspec 单元测试place method返回:truenil

班级

require 'active_model'
require_relative 'board'
require_relative 'direction'
require_relative 'report'

class Actions
    include ActiveModel::Validations

    attr_accessor :board

    def initialize
        @board = Board.new
        @move = Direction::Move.new
        @report = Report.new
    end

    def place(x_coordinate, y_coordinate, direction = :north)
        x_coordinate.between?(@board.left_limit, @board.right_limit) && 
        y_coordinate.between?(@board.bottom_limit, @board.top_limit) &&
        @move.directions.grep(direction).present?

        @report.log(x_coordinate, y_coordinate, direction)  
    end

end

Rspec 测试

require_relative '../spec_helper'
require 'board'
require 'actions'
require 'direction'

describe Board do

    let(:board) { Board.new }
    let(:action) { Actions.new }

    describe '#initialize' do
        it { expect(board.valid?).to be_true }
        it { expect(action.valid?).to be_true }
    end

    describe 'validations' do
        it 'should not exceed top limit' do
            expect(action.place(1, 6)).to be_false
        end 

        it 'should not exceed bottom limit' do
            expect(action.place(1, 0)).to be_false
        end

        it 'should not exceed right limit' do
            expect(action.place(6, 1)).to be_false
        end

        it 'should not exceed left limit' do
            expect(action.place(0, 1)).to be_false
        end

        it 'should place robot within its limits' do
            expect(action.place(1, 1)).to be_true
        end

        it 'should not accept non-integer values' do
            expect{action.place('a', 'b')}.to raise_error(ArgumentError)
        end
    end

    describe 'actions' do
        it 'place the robot on the board facing south' do
            expect(action.place(1, 1, Direction::South)).to be_true
        end
    end

end

所有应该返回真值的测试都失败并返回 nil

如果通过验证,有没有办法返回 true?

4

1 回答 1

1

该方法place将返回您让它返回的任何内容,无论是使用显式的return,还是从方法中评估的最后一条语句中返回。目前,返回值是任何@report.log(x_coordinate, y_coordinate, direction)返回值。这可能总是nil(这又恰好匹配be_false,但不匹配be_true)。我看不出这个规范有什么问题。

测试失败是真实的,被测代码有错误。可能您应该将日志消息作为place方法中的第一条语句,如下所示:

def place(x_coordinate, y_coordinate, direction = :north)
    @report.log(x_coordinate, y_coordinate, direction)  

    x_coordinate.between?(@board.left_limit, @board.right_limit) && 
    y_coordinate.between?(@board.bottom_limit, @board.top_limit) &&
    @move.directions.grep(direction).present?
end
于 2013-08-25T16:16:58.413 回答