【发布时间】:2011-09-09 09:29:40
【问题描述】:
我知道我应该测试验证,但我正在学习,所以想知道为什么我的代码不起作用。
环境 Ruby 1.9.2、Rails 3.1、RSpect 2.6.4
我有一个产品模型:
class Product < ActiveRecord::Base
attr_accessor :title, :description, :image_url, :price
validates_presence_of :title, :description, :image_url, :message => "can't be blank"
validates_uniqueness_of :title, :message => "must be unique"
validates_numericality_of :price, :greater_than_or_equal_to => 0.01, :message => "must be a number greater than 0"
validates_format_of :image_url, :with => %r{\.(gif|jpg|png)$}i, :message => "is a invalid image file"
end
在 spec/models/product_spec.rb 中:
require 'spec_helper'
describe Product do
before(:each) do
@attr = {
:title => "Lorem Ipsum",
:description => "Wibbling is fun!",
:image_url => "lorem.jpg",
:price => 19.99
}
end
it "rejects duplicated titles" do
Product.create!(@attr)
product_with_duplicate_title = Product.new(@attr)
product_with_duplicate_title.should_not be_valid
end
end
当我运行 rack rspec 时,我得到了:
Failures:
1) Product should reject if the title is duplicated
Failure/Error: product_with_duplicate_title.should_not be_valid
expected valid? to return false, got true
# ./spec/models/product_spec.rb:26:in `block (2 levels) in <top (required)>
为什么?我也使用 factory_girl 进行了类似的尝试,并得到了相同的结果……其他测试(此处未包括)用于测试空白、有效图像文件名等,都有效。
提前感谢。
【问题讨论】:
标签: ruby-on-rails rspec2