问题是我预计第二个it
会失败,第三个会通过,但情况正好相反。2分及格,3分不及格。有人知道为什么吗?
规范/模型/user_spec.rb
require 'spec_helper'
describe User do
it 'has a valid factory' do
FactoryGirl.create(:user).should be_valid
end
it 'is invalid with empty email1' do
# I've also tried
# FactoryGirl.build(:user, email: nil, validation_scenario: 'create').should be_valid
FactoryGirl.build(:user, email: nil).should be_valid
end
it 'is invalid with empty email2' do
FactoryGirl.build(:user, email: nil).should_not be_valid
end
end
规范/工厂/user.rb
require 'faker'
FactoryGirl.define do
factory :user do |u|
u.email { Faker::Internet.email }
u.password 'password'
u.password_confirmation 'password'
end
end
模型/user.rb
class User < ActiveRecord::Base
attr_accessor :password, :validation_scenario
# validate on user create/update
with_options if: -> user { ['create', 'update'].include? user.validation_scenario } do |user|
user.validates_confirmation_of :password
user.validates_presence_of :password, :on => :before_create
user.validates_presence_of :email, :password
user.validates_uniqueness_of :email
user.validates_format_of :email, :with =>/.+@.+..+/i
end
# validate on resend email cofirmation/reset password
with_options if: -> user { ['send_email_confirmation', 'reset_password'].include? user.validation_scenario } do |user|
user.validates_presence_of :email
user.validates_format_of :email, :with =>/.+@.+..+/i
end
...
控制器/user_controller.rb
class UsersController < ApplicationController
def create
@user = User.new(user_params)
@user.validation_scenario = 'create'
respond_to do |format|
if @user.save
format.html { redirect_to root_url, notice: 'User was successfully created.' }
else
format.html { render action: 'new' }
end
end
end
def user_params
params.require(:user).permit(:email, :password, :password_confirmation)
end
end
我在这里遵循这个教程:http://everydayrails.com/2012/03/19/testing-series-rspec-models-factory-girl.html
ruby 2.1.0p0 (2013-12-25 revision 44422) [x86_64-linux]
Rails 4.0.2事情是,我没有设置validation_scenario
任何地方。现在:
规范/工厂/用户。Rb看起来像这样:
require 'faker'
FactoryGirl.define do
factory :user do |u|
u.email { Faker::Internet.email }
u.password 'password'
u.password_confirmation 'password'
end
factory :create_user, parent: :user do |u|
u.validation_scenario 'create'
end
end
和规范/模型/user_spec.rb
require 'spec_helper'
describe User do
it 'has a valid factory' do
FactoryGirl.create(:create_user).should be_valid
end
it 'is invalid with empty email' do
FactoryGirl.build(:create_user, email: nil).should_not be_valid
end
it 'is invalid with empty password' do
FactoryGirl.build(:create_user, password: nil).should_not be_valid
end
it 'is invalid with empty password_confirmation' do
FactoryGirl.build(:create_user, password: nil).should_not be_valid
end
end
妙不可言