0

模型验证:

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?

规格:

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.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

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

4

0 回答 0