Why does this RSpec test not work?

I learn Ruby on Rails, so I treat me like a complete neophyte, because I am.

I have a User model with some related RSpec tests, and the following test fails:

require 'spec_helper'
describe User do

    it 'should require a password' do
        User.new({:email => 'valid_email@example.com', :password => '', :password_confirmation => ''}).should_not be_valid
    end

end

The relevant part of the model is Useras follows:

class User < ActiveRecord::Base
    ...
    validates :password, :presence => true,
                         :confirmation => true,
                         :length => { :minimum => 6 }
    ...
end

Here's the catch: if I started User.new(...).valid?from the Rails console using the above arguments, it returns false as expected and shows the correct errors (password is empty).

I used spork / autotest and I restarted both to no avail, but this test also does not allow to run it directly with rspec. What am I doing wrong here?

EDIT

I tried a few more things with the test. This fails:

        u = User.new({:email => 'valid_email@example.com', :password => '', :password_confirmation => ''})
        u.should_not be_valid

So does it:

        u = User.new({:email => 'valid_email@example.com', :password => '', :password_confirmation => ''})
        u.valid?
        u.errors.should_not be_empty

, , :password :

        u = User.new({:email => 'valid_email@example.com', :password => '', :password_confirmation => ''})
        u.password.should == ''
+3
2

, spork, . , :

http://ablogaboutcode.com/2011/05/09/spork-testing-tip-caching-classes

, :

ruby-1.9.2-p180 :020 > u = User.new
 => #<User id: nil, email: ...
ruby-1.9.2-p180 :021 > u.errors
 => {} 
ruby-1.9.2-p180 :022 > u.save
 => false 
ruby-1.9.2-p180 :023 > u.errors
 => {:email=>["can't be blank", "can't be blank"], ...} 

, , :) , , matcher be_valid . , , create , .

EDIT: be_valid_verbose, . be_valid_verbose.rb rspec/custom_matchers :

RSpec::Matchers.define :be_valid_verbose do
  match do |model|
    model.valid?
  end

  failure_message_for_should do |model|
    "#{model.class} expected to be valid but had errors:n #{model.errors.full_messages.join("n ")}"
  end

  failure_message_for_should_not do |model|
    "#{model.class} expected to have errors, but it did not"
  end

  description do
    "be valid"
  end
end

be_valid_verbose be_valid. , ​​ , .

+2

, . spork. , rspec , , spork , rspec . spork ( ) .

, , rspec , , , , . , spork, , -, , .

0

All Articles