RSPEC测试传递应该失败

时间:2011-09-13 20:02:17

标签: ruby-on-rails rspec

我正在使用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,则会变为红色。提前谢谢!

1 个答案:

答案 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
  • 向您显示您只指定了一个失败案例,并没有针对肯定案例(或其他案例)进行测试

如果你写了肯定的案例并且过去了那么你真的知道出了什么问题!