为什么这个测试不应该通过'?

时间:2013-09-05 03:26:41

标签: ruby-on-rails activerecord rspec

所以我有以下测试:

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)

创建的

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分: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 

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