【发布时间】:2010-08-31 10:07:15
【问题描述】:
通过 rspec(我正在使用 rspec-1.3.0、rspec-rails-1.3.2 gems)生成器 (ruby script/generate rspec_model suggestion section_id:integer user_id:integer subject:string content:text state:string type:string) 我创建了模型和模型规范并运行 rake db:migrate and rake:test:prepare
之后我开始研究我的模型规范:
require 'spec_helper'
describe Suggestion do
before(:each) do
@valid_attributes = {
:section_id => 1,
:user_id => 1,
:subject => 'Inappropriate title',
:content => 'The title of this section is inappropriate.',
:state => 'new',
:type => 'flag'
}
end
it "should create a new instance given valid attributes" do
Suggestion.create!(@valid_attributes)
end
it "should reject empty section_id attribute" do
empty_section_id_suggestion = Suggestion.new(@valid_attributes.merge(:section_id => ""))
empty_section_id_suggestion.should_not be_valid
end
...
除了第一个 "should create a new instance given valid attributes" 测试我创建了 6 个测试,基本上每个建议模型的测试属性为空 - 几乎与 "should reject empty section_id attribute" 示例完全相同。
当我运行测试时,我得到了 6 个失败的测试,这很好。第一次测试"should create a new instance given valid attributes" 通过。
现在,当我使用建议模型并添加 validates_presence_of :all 时,我收到以下与第一次测试相关的错误消息:
ActiveRecord::RecordInvalid in 'Suggestion should create a new instance given valid attributes'
Validation failed: All can't be blank
./spec/models/suggestion_spec.rb:16:
当我尝试单独运行测试 (validates_presence_of :attribute) 时,所有测试都通过了,只有 :type 属性我再次收到类似的错误消息:
ActiveRecord::RecordInvalid in 'Suggestion should create a new instance given valid attributes'
Validation failed: Type can't be blank
./spec/models/suggestion_spec.rb:16:
我以前没有遇到过这个问题(有多个相似的模型和它们的规格都通过了)。看起来它的 :type 属性有问题(它说它不能为空),即使我通过@valid_attributes 将值传递给它。我尝试谷歌搜索,但没有找到类似的问题/解决方案。
这里是 :type 属性的测试
it "should reject empty type attribute" do
empty_type_suggestion = Suggestion.new(@valid_attributes.merge(:type => ""))
empty_type_suggestion.should_not be_valid
end
请检查一下,让我知道我在这里做错了什么。
非常感谢您的帮助
彼得
【问题讨论】:
标签: ruby-on-rails validation activerecord rspec