测试 名字,很重要

nevill · 2012年10月11日 · 最后由 hooopo 回复于 2012年10月12日 · 2822 次阅读

这么一段代码

# notifications.rb
class Notification < ActiveRecord::Base
  attr_accessible :content, :checked
  belongs_to :sender, class_name: User, foreign_key: :sender_id
  belongs_to :receiver, class_name: User, foreign_key: :receiver_id

  scope :new, where(checked: false)
end

# factories.rb
  factory :notification do
    checked false
    content { "A test notification" }
    sender  user
    receiver tester
  end

尝试用 FactorGirl 来产生一个测试对象死活成功不了,在 Console 里面看是这样的

1.9.3p194 :001 > noti = FactoryGirl.create(:notification)
NoMethodError:   Notification Load (0.2ms)  SELECT "notifications".* FROM "notifications" WHERE "notifications"."checked" = 'f'
undefined method `checked=' for []:ActiveRecord::Relation
    from /Users/nevill/.rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.8/lib/active_record/relation/delegation.rb:45:in `method_missing'
    from /Users/nevill/.rvm/gems/ruby-1.9.3-p194/gems/factory_girl-2.3.2/lib/factory_girl/proxy.rb:132:in `block in assign_object_attributes'
    from /Users/nevill/.rvm/gems/ruby-1.9.3-p194/gems/factory_girl-2.3.2/lib/factory_girl/proxy.rb:131:in `each'
    from /Users/nevill/.rvm/gems/ruby-1.9.3-p194/gems/factory_girl-2.3.2/lib/factory_girl/proxy.rb:131:in `assign_object_attributes'
    from /Users/nevill/.rvm/gems/ruby-1.9.3-p194/gems/factory_girl-2.3.2/lib/factory_girl/proxy.rb:107:in `object'
    from /Users/nevill/.rvm/gems/ruby-1.9.3-p194/gems/factory_girl-2.3.2/lib/factory_girl/proxy.rb:84:in `result_instance'
    from /Users/nevill/.rvm/gems/ruby-1.9.3-p194/gems/factory_girl-2.3.2/lib/factory_girl/proxy/build.rb:11:in `result'
    from /Users/nevill/.rvm/gems/ruby-1.9.3-p194/gems/factory_girl-2.3.2/lib/factory_girl/proxy/create.rb:5:in `result'
    from /Users/nevill/.rvm/gems/ruby-1.9.3-p194/gems/factory_girl-2.3.2/lib/factory_girl/factory.rb:163:in `run'
    from /Users/nevill/.rvm/gems/ruby-1.9.3-p194/gems/factory_girl-2.3.2/lib/factory_girl/factory.rb:47:in `run'
    from /Users/nevill/.rvm/gems/ruby-1.9.3-p194/gems/factory_girl-2.3.2/lib/factory_girl/syntax/methods.rb:148:in `run_factory_girl_proxy'
    from /Users/nevill/.rvm/gems/ruby-1.9.3-p194/gems/factory_girl-2.3.2/lib/factory_girl/syntax/methods.rb:63:in `create'
    from (irb):1
    from /Users/nevill/.rvm/gems/ruby-1.9.3-p194/gems/railties-3.2.8/lib/rails/commands/console.rb:47:in `start'
    from /Users/nevill/.rvm/gems/ruby-1.9.3-p194/gems/railties-3.2.8/lib/rails/commands/console.rb:8:in `start'
    from /Users/nevill/.rvm/gems/ruby-1.9.3-p194/gems/railties-3.2.8/lib/rails/commands.rb:41:in `<top (required)>'

今天又仔细看了一下,忽然灵光一闪,把这句改了就成功啦

scope :unread, where(checked: false)

总结:起名是个大学问

晕...用 new 当然不行

#1 楼 @fresh_fish 是的,还写了一个 notification_spec.rb 都没有执行。。。其实,一跑测试都就会报一堆错误

我是看到楼主头像才点进来的

受教了,还有这个陷阱

坑爹的保留字 关键字

还有 first last 什么的

需要 登录 后方可回复, 如果你还没有账号请 注册新账号