应该是单元测试中的超类不匹配

时间:2011-06-27 18:28:40

标签: ruby ruby-on-rails-3 unit-testing shoulda

尝试使用shoulda和rails 3编写简单的单元测试。

测试/单元/ user_test.rb

class UserTest < Test::Unit::TestCase
  should validate_presence_of(:password, :on => :create)
  should validate_presence_of(:handle, :email)
  should validate_confirmation_of(:password)
  should validate_length_of(:handle, :within => 6..15)
  should validate_uniqueness_of(:handle)
  should validate_format_of(:handle, :with => /\A\w+\z/i)
  should validate_length_of(:email, :within => 6..100)
end

Gemfile

的相关部分
group :test do
  gem 'shoulda'
  gem 'rspec-rails', '2.0.0.beta.12'
end

当我尝试使用rake test --trace运行此操作时,收到以下错误:

** Execute test:units
/Users/removed/removed/removed/app_name/test/unit/user_test.rb:5: superclass mismatch for class UserTest (TypeError)
    from /Library/Ruby/Gems/1.8/gems/activesupport-3.0.7/lib/active_support/dependencies.rb:239:in `require'
    from /Library/Ruby/Gems/1.8/gems/activesupport-3.0.7/lib/active_support/dependencies.rb:239:in `require'
    from /Library/Ruby/Gems/1.8/gems/activesupport-3.0.7/lib/active_support/dependencies.rb:227:in `load_dependency'
    from /Library/Ruby/Gems/1.8/gems/activesupport-3.0.7/lib/active_support/dependencies.rb:239:in `require'
    from /Library/Ruby/Gems/1.8/gems/rake-0.9.2/lib/rake/rake_test_loader.rb:9
    from /Library/Ruby/Gems/1.8/gems/rake-0.9.2/lib/rake/rake_test_loader.rb:9:in `each'
    from /Library/Ruby/Gems/1.8/gems/rake-0.9.2/lib/rake/rake_test_loader.rb:9
    from /Library/Ruby/Gems/1.8/gems/rake-0.9.2/lib/rake/rake_test_loader.rb:5:in `each'
    from /Library/Ruby/Gems/1.8/gems/rake-0.9.2/lib/rake/rake_test_loader.rb:5

我理解错误,我只是不知道另外一个UserTest类会定义给我这个问题。有什么想法吗?

麦克

2 个答案:

答案 0 :(得分:5)

检查find . | xargs grep -l UserTest的输出,防止意外重复使用类名。

答案 1 :(得分:0)

我能想象避免这个错误的唯一方法是做以下事情:

UserTest = Class.new(Test::Unit::TestCase)
class UserTest # Or class UserTest < Test::Unit::TestCase is also allowed
  should validate_presence_of(:password, :on => :create)
  should validate_presence_of(:handle, :email)
  should validate_confirmation_of(:password)
  should validate_length_of(:handle, :within => 6..15)
  should validate_uniqueness_of(:handle)
  should validate_format_of(:handle, :with => /\A\w+\z/i)
  should validate_length_of(:email, :within => 6..100)
end

如果你要重复

UserTest = Class.new(Test::Unit::TestCase) # repeated

你会得到

warning: already initialized constant UserTest

但这种做法看起来有点奇怪。