【问题标题】:Rspec test for validity of new object not passingRspec 测试新对象的有效性未通过
【发布时间】:2012-09-27 14:56:14
【问题描述】:

我完成了 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

当我从charity.rb 中删除:name:summary:description 验证时,测试通过了。为了更好的衡量,这是我user.rb的开头:

class User < ActiveRecord::Base
  attr_accessible :name, :email, :password, :password_confirmation 
  has_secure_password
  has_many :charities
  has_many :microposts, dependent: :destroy

【问题讨论】:

    标签: ruby-on-rails rspec factory-bot railstutorial.org


    【解决方案1】:

    利用您的工厂进行适当的慈善活动:

    before { @charity = user.charities.build(FactoryGirl.attributes_for(:charity)) }
    

    它失败了,因为您验证了未设置的属性的存在,例如 name

    如果您需要更多有关 FactoryGirl 的背景知识,他们的documentation 非常好。

    【讨论】:

      猜你喜欢
      • 2017-01-24
      • 1970-01-01
      • 1970-01-01
      • 2020-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多