所以我有以下测试:
it "should not update a user based on invalid info" do
put :update, :id => @factory.id, :user => {
:name => '', :user_name => '',
:email => '', :email_confirmation => '',
:password => '', :password_confirmation => 'dfgdfgdfg',
:bio => '', :picture_url => ''
}
end
这显然有缺失的数据。
然后我有以下控制器:
def update
@user = User.friendly.find(params[:id])
@user.update_attributes(user_update_params)
if @user.save
render :show
else
render :edit
end
end
这具有以下私有方法:
def user_update_params
params.require(:user).permit(:name, :user_name, :email, :email_confirmation, :password,
:password_confirmation, :bio, :picture_url)
end
当这个测试运行它通过 - 它应该给我一个ActiveRecord::RecordInvalid
如果您感兴趣,这是模型:
class User < ActiveRecord::Base
attr_accessor :password
before_save :encrypt_password
validates :name, uniqueness: true, presence: true
validates :user_name, uniqueness: true, presence: true, length: {minimum: 5}
validates :email, presence: true, confirmation: true, uniqueness: true, email_format: {message: "what is this? it's not an email"}
validates :password, presence: true, confirmation: true, length: {minimum: 10}
extend FriendlyId
friendly_id :name, use: [:slugged, :history]
def self.authenticate(user_name, password)
user = User.find_by(user_name: user_name)
if(user && user.password_hash == BCrypt::Engine.hash_secret(password, user.salt))
user
else
nil
end
end
def encrypt_password
if password.present?
self.salt = BCrypt::Engine.generate_salt
self.password_hash = BCrypt::Engine.hash_secret(password, salt)
end
end
end
我也打赌它是非常微不足道的
更新如果您感兴趣,这是我的工厂:
FactoryGirl.define do
factory :user, :class => 'User' do
name "sample_user"
email "MyString@gmail.com"
user_name "MyString"
password "someSimpleP{ass}"
end
end
所以@factory
是从@factory = FactoryGirl.create(:user)