这是我的模特:
class Restaurant < ActiveRecord::Base
validate :name, presence: true, uniqueness: { case_sensitive: false }
end
以下是测试:
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
当我运行测试时,我会失败:
$ 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
为什么?
答案 0 :(得分:1)
使用验证而不是验证。