【问题标题】:rspec testing model validations with subject - errorrspec 使用主题测试模型验证 - 错误
【发布时间】:2011-12-30 01:00:01
【问题描述】:

这是我的验证测试,我想找到编写模型规范的最佳方法,尤其是验证。但我对下面的这段代码有疑问。

require 'spec_helper'

describe Ad, :focus do
  let(:ad) { Ad.sham!(:build) }

  specify { ad.should be_valid }

  it "not creates a new instane given a invalid attribute" do
    ad = Ad.new
    ad.should_not be_valid
  end

  [:title, :category_id, :email, :ad_content, :name, :price].each do |attr|
    it "should require a #{attr}" do
      subject.errors[attr].should include("blank") 
    end
  end    
end

当我运行这个规范时,我收到了这个错误:

   5) Ad should require a name
     Failure/Error: subject.errors[attr].should include("blank")
       expected [] to include "blank"
       Diff:
       @@ -1,2 +1,2 @@
       -blank
       +[]
     # ./spec/model/ad_spec.rb:15:in `block (3 levels) in <top (required)>'

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 validation rspec


    【解决方案1】:

    这里的问题是您在检查错误之前没有调用valid? 在该示例中。您在上一个示例中(间接地)调用它,但不是您断言有错误的那个。

    正确的做法是这样的:

    [:title, :category_id, :email, :ad_content, :name, :price].each do |attr|
      it "should require a #{attr}" do
        subject.valid?
        subject.errors[attr].should include("blank")
      end
     end
    

    【讨论】:

      猜你喜欢
      • 2015-10-22
      • 2011-11-24
      • 2017-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多