0

所以我有以下测试:

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)

4

2 回答 2

2

您正在执行一个 RSpec 方法 ( put),只要参数格式正确,就不会引发错误,以便可以将消息发送到服务器。由于您的论点本身没有问题,因此没有引发错误。服务器无法成功完成请求将反映在响应中,您需要单独测试。

当然,正如其他人所指出的那样,在 RSpec 示例中通常会在代码上设置“期望”,这将确定示例是否成功,因此不仅仅是没有未捕获的错误将确定成功。

于 2013-09-05T05:33:22.163 回答
0

不是考试不通过,而是没有考试。你错过了测试中的期望。尝试这样的事情。

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 => ''
    }
    #add expectation here
    response.should_not be_valid
end 

任何没有期望的测试都会通过。

于 2013-09-05T04:25:05.113 回答