Pregunta

Here is my model:

class Restaurant < ActiveRecord::Base
    validate :name, presence: true, uniqueness: { case_sensitive: false }
end

Here are test:

require 'spec_helper'

describe Restaurant do
    before do
        @restaurant = Restaurant.new(name: "Momofuku")
    end

    subject { @restaurant }

    it { should respond_to(:name) }
    it { should be_valid }

    describe "when name is not present" do
        before { @restaurant.name = " " }
        it { should_not be_valid}
    end

    describe "when name is already taken" do
        before do
            restaurant_with_same_name = @restaurant.dup
            restaurant_with_same_name.name = @restaurant.name.upcase
            restaurant_with_same_name.save
        end

        it { should_not be_valid }
    end
end

When I am running the test I get failures:

$ bundle exec rspec spec/models
..FF

Failures:

  1) Restaurant when name is not present should not be valid
     Failure/Error: it { should_not be_valid}
       expected #<Restaurant id: nil, name: " ", created_at: nil, updated_at: nil> not to be valid
     # ./spec/models/restaurant_spec.rb:15:in `block (3 levels) in <top (required)>'

  2) Restaurant when name is already taken should not be valid
     Failure/Error: it { should_not be_valid }
       expected #<Restaurant id: nil, name: "Momofuku", created_at: nil, updated_at: nil> not to be valid
     # ./spec/models/restaurant_spec.rb:25:in `block (3 levels) in <top (required)>'

Finished in 0.01879 seconds
4 examples, 2 failures

Failed examples:

rspec ./spec/models/restaurant_spec.rb:15 # Restaurant when name is not present should not be valid
rspec ./spec/models/restaurant_spec.rb:25 # Restaurant when name is already taken should not be valid

Randomized with seed 39746

Why ?

¿Fue útil?

Solución

Use validates instead of validate.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top