【发布时间】:2010-03-10 11:20:04
【问题描述】:
我无法让 rspec 正常运行以测试 validates_inclusion_of 我的迁移如下所示:
class CreateCategories < ActiveRecord::Migration
def self.up
create_table :categories do |t|
t.string :name
t.integer :parent_id
t.timestamps
end
end
def self.down
drop_table :categories
end
end
我的模型如下所示:
class Category < ActiveRecord::Base
acts_as_tree
validates_presence_of :name
validates_uniqueness_of :name
validates_inclusion_of :parent_id, :in => Category.all.map(&:id), :unless => Proc.new { |c| c.parent_id.blank? }
end
我的工厂:
Factory.define :category do |c|
c.name "Category One"
end
Factory.define :category_2, :class => Category do |c|
c.name "Category Two"
end
我的模型规格如下所示:
require 'spec_helper'
describe Category do
before(:each) do
@valid_attributes = {
:name => "Category"
}
end
it "should create a new instance given valid attributes" do
Category.create!(@valid_attributes)
end
it "should have a name and it shouldn't be empty" do
c = Category.new :name => nil
c.should be_invalid
c.name = ""
c.should be_invalid
end
it "should not create a duplicate names" do
Category.create!(@valid_attributes)
Category.new(@valid_attributes).should be_invalid
end
it "should not save with invalid parent" do
parent = Factory(:category)
child = Category.new @valid_attributes
child.parent_id = parent.id + 100
child.should be_invalid
end
it "should save with valid parent" do
child = Factory.build(:category_2)
child.parent = Factory(:category)
# FIXME: make it pass, it works on cosole, but I don't know why the test is failing
child.should be_valid
end
end
我收到以下错误:
'类别应保存为有效 parent' FAILED 预期 #
是有效的,但它不是错误: 父母失踪
在控制台上一切似乎都很好并且按预期工作:
c1 = Category.new :name => "Parent Category"
c1.valid? #=> true
c1.save #=> true
c1.id #=> 1
c2 = Category.new :name => "Child Category"
c2.valid? #=> true
c2.parent_id = 100
c2.valid? #=> false
c2.parent_id = 1
c2.valid? #=> true
我正在运行 rails 2.3.5、rspec 1.3.0 和 rspec-rails 1.3.2
任何人,有什么想法吗?
【问题讨论】:
标签: ruby-on-rails ruby validation rspec