Rails:应该匹配并验证更新时的用户名

时间:2013-09-03 19:04:18

标签: ruby-on-rails tdd rspec-rails shoulda

模型验证:

validates :username, uniqueness: true, format: { with: /\A[a-zA-Z0-9_.-@]+\Z/i, message: "must contain only letters, numbers or _*-@" }, on: :update, :if => :username_changed?

Rspec的:

require 'spec_helper'

describe User, "references" do
  it { should have_and_belong_to_many(:roles) }
  it { should belong_to(:account_type) }
  it { should belong_to(:primary_sport).class_name("Sport") }
  it { should belong_to(:school) }
  it { should belong_to(:city) }
  it { should validate_presence_of(:email) }
  it { should validate_uniqueness_of(:email) }
  it { should allow_value("test@test.com").for(:email) }
  it { should_not allow_value("test.com").for(:email) }

  describe "validation of username", focus: true do
    before(:each) do
      @user = User.new(email: Faker::Internet.email, password: "password", password_confirmation: "password", username: "test123", agreed_to_age_requirements: true)
    end

    it "should be valid" do
      @user.save
      @user.should be_valid
    end

    it "should not be valid with incorrect characters in username" do
      @user.username = "test@@@!!!"
      @user.should_not be_valid
    end
  end
end

FactoryGirl:

FactoryGirl.define do
  factory :user do
    email Faker::Internet.email
    password "password"
    password_confirmation "password"
    agreed_to_age_requirements true
    username Faker::Internet.user_name
  end 
end

我基本上只是尝试针对用户名的指定格式的唯一性进行自定义验证测试

0 个答案:

没有答案