为什么这个测试在不应该通过的时候通过了?



所以我有以下测试:

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)创建的

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

当然,正如其他人指出的那样,在 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 => ''
    }
    #add expectation here
    response.should_not be_valid
end 

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

最新更新