为什么我的条件验证失败了?

时间:2011-09-17 15:35:15

标签: 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 => "", :post_type => "text"))
  post.should_not be_valid

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

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

1 个答案:

答案 0 :(得分:0)

你必须在某处失败才能进行其他验证。进入rails控制台并执行:

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

看看你得到了什么......