gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 07:12:20 25 4
gpt4 key购买 nike

我使用 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

最佳答案

这是一个例子......按照惯例,主题被填充为“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/

关于ruby-on-rails - 如何为空白字段编写 rspec? [Rails3.1],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7712867/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com