¿Por qué rspec me dice que este usuario es válido?

I have the following classes in Rails and am writing some rspec tests (any critiques are more than welcome as I'm a nOOb at rspec).

class User.rb

class User < ActiveRecord::Base

email_regex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i

validates :email, :presence   => true ,
                  :format     => { :with => email_regex },
                  :uniqueness => { :case_sensitive => true },
                  :on => :create

and in factories.rb

FactoryGirl.define do
  factory :user do
    sequence(:name) { |n| "my-name#{n}" }
    sequence(:email) { |n| "blue#{n}@12blue.com" }

and in my rspec (users_spec.rb):

require 'spec_helper'

describe User do
  let(:user) { FactoryGirl.build(:user) }
  it { user.should be_valid }
  it { user.should be_a(User) }
  it { user.should respond_to(:email) }

  it { user.email = " " }
  it { user.should_not be_valid } # this is causing the error 

y obten

1) User 
     Failure/Error: it { user.should_not be_valid }
       expected valid? to return false, got true

But based upon the validates, user should be not be valid. What is going on here? What am I not getting (and I know it's my fault)?


preguntado el 25 de agosto de 12 a las 05:08

1 Respuestas

I assume that the test failure surprises you because you think the user email should be " ".

In rspec every example is independent. This means that anything you did in a previous example is forgotten.

In your case your second to last example runs, builds a new, valid activerecord user whose email is "blue4@12blue.com", overwrites that email with " " and then passes since it makes no assertions.

Then your last example runs, builds a new, valid activerecord user who's email is "blue5@12blue.com" and fails because the user is valid, it's email has not been overwritten.

Probablemente quieras algo como esto:

it 'should validate the email' do
  user.email = " "
  user.should_not be_valid

Respondido 25 ago 12, 05:08

thx, makes more sense. Could I wrap them with a structure like a 'describe' to put those two together? - timpón

Not with a describe, no. describe and context are meant to wrap groups of examples (relishapp.com/rspec/rspec-core/v/2-11/docs/example-groups/…). Instead remember that you can put more than one line of code in an example block. I've added an example to my answer that should do what you want. Hope that helps. - Gordon Wilson

thx, makes more sense now - will probably have a bunch of other questions as some of this is a little abstract. - timpón

Feel free to ask them. I'll check back in a few to answer. - Gordon Wilson

Yes, you can customize the error messages for most rspec expectations. For example, user.should_not be_valid, "User was unexpectedly valid, #{user.attributes.inspect}". relishapp.com/rspec/rspec-expectations/docs/customized-message - Gordon Wilson

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.