-1

我正在尝试使用 R-Spec 进行单元测试时出错,但这不起作用。

我有以下代码使用活动模型来验证最大值和最小值,如下所示:

require 'active_model'

class Board < Struct.new(:width, :height)
    include ActiveModel::Validations

    attr_reader :top_limit, :bottom_limit, :left_limit, :right_limit

    validate :top_limit,    presense:true, numerically: {only_integer: true, :less_than => 6}
    validate :bottom_limit, presense:true, numerically: {only_integer: true, :greater_than => 0}
    validate :left_limit,   presense:true, numerically: {only_integer: true, :greater_than => 0}
    validate :right_limit,  presense:true, numerically: {only_integer: true, :less_than => 6}

    def place(x, y)

    end

end

对于下面的测试:

require_relative '../spec_helper'
require 'board'

describe Board do

    before do
        @board = Board.new
    end

    describe 'initialise' do

        it 'should not exceed top limit' do
            @board.place(1, 6).should raise_error
        end

        it 'should not exceed bottom limit' do
            @board.place(1, 0).should raise_error
        end

        it 'should not exceed right limit' do
            @board.place(6, 1).should raise_error
        end

        it 'should not exceed left limit' do
            @board.place(0, 1).should raise_error
        end

        it 'should place robot within its limits' do
            @board.place(1, 1).should_not raise_error
        end

    end

end

如何使用 Active Model 验证输入@board.place

4

2 回答 2

1

You need to call valid? somehow. Basically right now, your tests are just instantiating a Board and calling the place method.

You could do the following in your spec:

let(:instance) { Board.new }

it { expect(instance.valid?).to be_false }

Also, your validations are wrong:

validates :top_limit, presence: true, numericality: { only_integer: true, less_than: 6 }
        ^                   ^         ^^^^^^^^^^^^  
于 2013-08-18T19:17:10.123 回答
0

numerically should probably be numericality.

Also, you aren't actually validating anywhere, you've just declared the validations.

If you want your place method to raise errors and pass the tests, you need to add some code in there. If that is what your question really is about, please post what you have tried that didn't work.

于 2013-08-18T19:18:55.627 回答