Ruby Rspec在方法验证后返回nil

时间:2013-08-25 16:09:59

标签: ruby rspec

我正在尝试使用place method下方的true代替nil来自Rspec单元测试:

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

所有应返回true值的测试都会失败并返回nil

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

1 个答案:

答案 0 :(得分:1)

方法place将返回您返回的任何内容,使用显式return或从方法中评估的最后一个语句返回。目前,返回值是@report.log(x_coordinate, y_coordinate, direction)返回的任何值。这可能总是nil(反过来恰好匹配be_false,但不匹配be_true)。我没有看到任何错误的规格。

测试失败是真实的,测试中的代码有一个bug。您可能只需将日志消息作为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