0

这是我的规格文件:

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) }
end 

describe User, "factory" do
  before(:each) do
    @user = FactoryGirl.create(:user)
  end

  it "is invalid with no email" do
    @user.email = nil
    @user.should_not be_valid
  end

  it "is valid with email" do
    @user.should be_valid
  end
end

工厂:

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

我试图“测试”但不确定如何 100% 的部分是检查以确保在创建用户时电子邮件地址不为零。

4

1 回答 1

2

shoulda提供验证助手来帮助您测试验证。

it { should validate_presence_of(:email) }

如果您想使用 rspec 并自己编写,那么

describe User do
  it "should be invalid without email" do
    user = FactoryGirl.build(:user, :email => nil)
    @user.should_not be_valid
    @user.errors.on(:email).should == 'can't be blank' #not sure about the exact message. But you will know when you run the test
  end

  it "should be valid with email" do
    user = FactoryGirl.build(:user, :email => "user@user.com")
    @user.should be_valid
  end
end

当您运行测试时,它会读取为

User
  should be invalid without email
  should be valid with email

为您的测试用例提供一个好的描述非常重要,因为它有点像文档。

于 2013-09-03T18:39:31.413 回答