RSpec 2测试唯一性

T10*_*000 1 ruby-on-rails rspec2

我知道我应该测试验证,但我正在学习,所以想知道为什么我的代码不起作用.

环境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
Run Code Online (Sandbox Code Playgroud)

在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
Run Code Online (Sandbox Code Playgroud)

当我运行机架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)>
Run Code Online (Sandbox Code Playgroud)

为什么?我也尝试使用factory_girl类似的东西,并得到了相同的结果...其他测试(不包括在这里)测试空白,有效的图像文件名等,都工作.

Thanx提前.

apn*_*ing 9

你最好遵循一条更容易的道路:使用shoulda匹配器和Rspec.你最终只是写作:

describe Product do
  it { should validate_uniqueness_of(:title) }
end
Run Code Online (Sandbox Code Playgroud)

在这里.