0

我希望有人会发现为什么这不起作用。

我收到一个错误,因为我使用 Factory_Girl 指定的属性在验证之前未应用于存根。

错误:

undefined method `downcase' for #<Category:0x1056f2f60>

RSpec2

it "should vote up" do
  @mock_vote = Factory.create(:vote)
  Vote.stub(:get_vote).and_return(@mock_vote)
  get :vote_up, :id => "1"        
end

工厂

Factory.define :vote, :class => Vote do |v|
  v.user_id "1"
  v.association :post
end

Factory.define :post, :class => Post do |p|
  p.category "spirituality"
  p.name "sleezy snail potluck"
  p.association :category
end

Factory.define :category, :class => Category do |c|
  c.name "spirituality"
  c.id "37"
end

Post.rb - 模型

before_save           :prepare_posts
validate              :category?

def prepare_posts
  self.update_attribute("category", self.category.downcase)
  if self.url?
    self.url = "http://" + self.url unless self.url.match /^(https?|ftp):\/\//
  end
end

def category?
  unless Category.exists?(:name => self.category.downcase)
    errors.add(:category, "There's no categories with that name.")
  end
  return true
end

此外,请随意挑剔任何看起来很粗暴的代码。:D

谢谢!!

4

1 回答 1

2

您有一个category属性,它似乎是一个字符串,但您似乎也有一个类别关联,它会自动在 Post 上创建一个名为 的属性category,可能会覆盖您的类别属性。因此,Category该类没有downcase方法,因为它不是字符串。

将您的类别属性重命名为category_name,但实际上您根本不应该拥有该属性。

也许你打电话给self.category.downcase你的意思是self.category.name.downcase什么?

于 2010-09-13T01:58:55.807 回答