我完成了 Michael Hartl 的所有 Ruby on Rails 教程,所有测试都通过了。现在我要回去对网站进行更改以满足我自己的需要,它并不像“本节中的测试没有通过”那么简单。我创建了一个基于 Hartl 的“Micropost”对象的新“Charity”对象。唯一的区别是对象没有“内容”,而是有:name,:description和:summary。
这是失败的测试代码(特别是“it { should be_valid }”),位于/charity_spec.rb:
require 'spec_helper'
    describe Charity do
      let(:user) { FactoryGirl.create(:user) }
      before { @charity = user.charities.build(summary: "Lorem ipsum") }
      subject { @charity }
      it { should respond_to(:name) }
      it { should respond_to(:user_id) }
      it { should respond_to(:summary) }
      it { should respond_to(:description) }
      it { should respond_to(:user) }
      its(:user) { should == user }
      it { should be_valid }
      ...
测试实际上首先通过了,但是一旦我将验证添加到charity.rb文件中,它们就会返回;
 Failures:
   1) Charity
      Failure/Error: it { should be_valid }
         expected valid? to return, true, got false
         ...
这是charity.rb:
class Charity < ActiveRecord::Base
  attr_accessible :name, :description, :summary
  belongs_to :user
  validates :name, presence: true, length: { maximum: 40 }
  validates :summary, presence: true
  validates :description, presence: true
  validates :user_id, presence: true
  default_scope order: 'charities.created_at DESC'
end
我敢肯定这是愚蠢的,但我对一切的理解是如此的薄弱,以至于我无法弄清楚我做错了什么,我的感觉是我的工厂出了问题,但我真的不知道。
这是我的慈善工厂位于factories.rb:
factory :charity do
    name "Lorem ipsum"
    summary "Lorem ipsum"
    description "Lorem ipsum"
    user
end
当我从 中删除:name、:summary和:description验证时charity.rb,测试通过。为了更好地衡量,这是我的开头user.rb:
class User < ActiveRecord::Base
  attr_accessible :name, :email, :password, :password_confirmation 
  has_secure_password
  has_many :charities
  has_many :microposts, dependent: :destroy