如何为空白字段编写rspec? [Rails3.1]

时间:2011-10-10 12:37:54

标签: ruby-on-rails ruby rspec

我使用rails 3.1 + rspec和factory girl。

我对必填字段的验证(validates_presence_of)正在运行。 如何将测试用作“成功”而非“失败”的测试 规范是:

describe "Add an industry with no name" do
  context "Unable to create a record when the name is blank" do
    subject do
      ind = Factory.create(:industry_name_blank)
    end
    it { should be_invalid }
  end
end

但是我失败了:

Failures:

  1) Add an industry with no name Unable to create a record when the name is blank 
     Failure/Error: ind = Factory.create(:industry_name_blank)
     ActiveRecord::RecordInvalid:
       Validation failed: Name can't be blank
     # ./spec/models/industry_spec.rb:45:in `block (3 levels) in <top (required)>'
     # ./spec/models/industry_spec.rb:47:in `block (3 levels) in <top (required)>'

Finished in 0.20855 seconds
8 examples, 1 failure

型号代码:

class Industry < ActiveRecord::Base
  validates_presence_of :name
  validates_uniqueness_of :name
end

工厂代码:

Factory.define :industry_name_blank, :class => 'industry' do |industry|
  industry.name   { nil }
end

2 个答案:

答案 0 :(得分:8)

这是一个例子......主题按照惯例填充“Industry.new”

describe Industry do

  it "should have an error on name when blank" do
    subject.name.should be_blank
    subject.valid?
    subject.should have(1).error_on(:name)
    #subject.errors.on(:name).should == "is required"
  end

end

最后一点比较脆弱,但是你可以做到这一点

有关语法的更多信息:http://cheat.errtheblog.com/s/rspec/

答案 1 :(得分:2)

Factory.build(:industry_name_blank)生成对象,而Factory.create(:industry_name_blank)生成并保存创建的对象。在您的情况下,它无法保存对象,因为它由于缺少name而无效,这就是您获得验证错误的原因。

因此,不要使用create使用build来避免遇到验证错误:Factory.build(:industry_name_blank)。然后你应该像杰西建议的那样指出它:

subject.should_not be_valid
subject.should have(1).error_on(:name)