-1

I'm trying to get error for my unit testing with R-Spec but this isn't working.

I have below code using active model to validate max and min values as per below:

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

For test below:

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

How can I use Active Model to validate the inputs of @board.place?

Passionate Engineer
  • 10,034
  • 26
  • 96
  • 168

2 Answers2

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 }
        ^                   ^         ^^^^^^^^^^^^  
Pierre-Louis Gottfrois
  • 17,561
  • 8
  • 47
  • 71
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.

Jakob S
  • 19,575
  • 3
  • 40
  • 38