我正在使用rspec,rails,guard和sorcery进行身份验证和测试。
我有一个测试电子邮件长度的测试。我想拒绝太长的电子邮件。这是我为spec / models / user_spec.rb
编写的测试 require 'spec_helper'
describe User do
before(:each) do
@attr = { :email => "testuser@example.com", :password => "password", :password_confirmation => "password" }
end
it "should reject emails that are too long" do
long_email = "a" * 101 + "gmail.com"
long_email = User.new (@attr.merge(:email => long_email))
long_email.should_not be_valid
end
以下是我的模型验证:
class User < ActiveRecord::Base
authenticates_with_sorcery!
attr_accessible :email, :password, :password_confirmation
validates_presence_of :password, :on => :create
validates :password, :confirmation => true,
:length => { :within => 6..100 }
email_regex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, :presence => true,
:format => { :with => email_regex },
:uniqueness => {:case_sensitive => false},
:length => { :within => 5..100 }
end
我是这个东西的菜鸟,所以任何帮助都会非常感激。测试现在为绿色,如果我将行更改为long_email.should be_valid,则会变为红色。提前谢谢!
答案 0 :(得分:1)
正如@apneadiving指出的那样,测试的格式很重要。它不仅使阅读更容易,而且还显示未经测试的地方:
require 'spec_helper'
describe User do
let(:attr){
{:email => "testuser@example.com", :password => "password", :password_confirmation => "password" }
}
context "When given an email address" do
context "That is too long" do
let(:long_email){ "a" * 101 + "gmail.com" }
subject{ User.new attr.merge(:email => long_email) }
specify{ subject.should_not be_valid }
end
context "That is too short" do
pending
end
context "That is between 5 and 100 characters long"
pending
end
end
end
正如您所看到的,重写它已经做了几件事:
let
代替before
)如果你写了肯定的案例并且过去了那么你真的知道出了什么问题!