简体   繁体   English

如何使用RSpec测试我的设计用户模型验证?

[英]How do I test my devise user model validations using RSpec?

I can find recommendations for testing devise user controllers and views in RSpec. 我可以在RSpec中找到有关测试设计用户控制器和视图的建议。 I've also seen suggestions that the devise gem code is already tested so it's not useful to spend a lot of time reinventing the wheel. 我还看到了一些建议,说明设计的gem代码已经过测试,因此花很多时间重新设计轮子没什么用。

However, my user model has other fields that I need validated when the user signs up. 但是,我的用户模型还有其他字段,当用户注册时需要验证。 I'm using standard validates... statements in the user.rb model. 我在user.rb模型中使用标准的validates...语句。 For example: 例如:

validates_presence_of     :nickname

I'm trying to use simple validation testing in my user_spec.rb, but when I try to create the user like this: 我正在尝试在user_spec.rb中使用简单的验证测试,但是当我尝试像这样创建用户时:

record = Factory.create(:user)

I get this error: 我收到此错误:

undefined method `encode!' for "Confirmation":String

The encode! encode! method is not coming from my code, it must be one of the gems that devise is using, but I haven't been able to find it, yet. 方法不是来自我的代码,它一定是devise正在使用的瑰宝之一,但是我还没有找到它。

I've tried creating the user using User.new and Factory Girl. 我尝试使用User.new和Factory Girl创建用户。 I get the same error either way. 无论哪种方式,我都会遇到相同的错误。 This spec was passing until I did an update of all my gems. 直到我对所有宝石进行了更新,该规范才通过。 Unfortunately I didn't keep a note of everything that got updated at the time. 不幸的是,我没有记下当时更新的所有内容。 I've tried rolling devise back to previous versions but still get the same error. 我尝试将设计回滚到以前的版本,但仍然遇到相同的错误。

Rails 3, RSpec2 Rails 3,RSpec2

Thanks for any advice. 感谢您的任何建议。

It seems to be fine, may be, my testing code helps you out: 也许很好,我的测试代码可以帮助您:

user_spec.rb user_spec.rb

require 'spec_helper'

describe User do
  before :each do
    @user = Factory.build(:user)
  end

  it "should not be valid without a first_name" do
    @user.first_name = nil
    @user.should_not be_valid
  end

end

user.rb (Model) user.rb(模型)

class User < ActiveRecord::Base

  validates_presence_of :first_name

  # Include default devise modules. Others available are:
  # :token_authenticatable, :confirmable, :lockable and :timeoutable
  devise :database_authenticatable, :registerable, :lockable,
         :recoverable, :rememberable, :trackable
  # Setup accessible (or protected) attributes for your model
  attr_accessible :login, :first_name, :email, :password, :password_confirmation, :remember_me
  attr_accessor :login

  devise :database_authenticatable, :recoverable, :validatable

  protected

  def password_required?
    !persisted? || password.present? || password_confirmation.present?
  end



end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM