Ruby on rails 为什么我的条件验证失败?

Ruby on rails 为什么我的条件验证失败?,ruby-on-rails,validation,rspec,ruby-on-rails-3.1,rspec2,Ruby On Rails,Validation,Rspec,Ruby On Rails 3.1,Rspec2,我的Post模型中有一个条件验证: validates :title, :presence => true, :if => Proc.new { |post| post.post_type == "text" } 我的post_spec.rb文件中有以下规范: it "should only require a title if the post type is text" do post = Post.new(@attr.merge(:title => "", :pos

我的Post模型中有一个条件验证:

validates :title, :presence => true, :if => Proc.new { |post| post.post_type == "text" }
我的
post_spec.rb
文件中有以下规范:

it "should only require a title if the post type is text" do
  post = Post.new(@attr.merge(:title => "", :post_type => "text"))
  post.should_not be_valid

  post = Post.new(@attr.merge(:title => "", :post_type => "image"))
  post.should be_valid # This fails
end

我的问题是:为什么第二次测试失败?

你必须有其他验证失败的地方。进入rails控制台并执行以下操作:

post = Post.new(:title => "", :post_type => "image")
post.valid?
post.errors

看看你得到了什么…

我们是否应该假设没有其他验证会失败,并且
@attr
中的剩余值是有效的?是的,如果我从第二次后期创建中删除空标题,验证就会通过。因此,失败的是标题验证,其他的都是有效的。如果您将规则更改为类似于
post.errors.should\u empty
的内容,您至少会得到更具描述性的失败。(甚至是
post.errors[:title]
,因为这就是你要测试的)@numbers1311407:这是奇怪的部分,如果我照你说的做,测试通过了,但是帖子无效,只是没有任何错误消息,这真的很奇怪……你的模型中还有什么其他东西,比如
attr\u accessible
/
attr\u protected