0

我试图在 Rails 测试中模仿类似枚举的效果。但是,我似乎无法让它工作。

例子。

我有一个名为 Days 的模块:

module Days    
   SUNDAY = 0;
   MONDAY = 1;
   TUESDAY = 2;
   WEDNESDAY = 3;
   THURSDAY = 4;
   FRIDAY = 5;
   SATURDAY = 6;
end

在同一目录中,我有一个 scheduler_spec.rb

require 'spec_helper'
describe Scheduler do
  include Days
  ... 

但是,Ruby 会抛出以下错误:

in `block in <top (required)>': uninitialized constant Days (NameError)
    from /Users/krg07/.rvm/gems/ruby-1.9.3-p125/gems/rspec-core-2.9.0/lib/rspec/core/example_group.rb:201:in `module_eval'
    from /Users/krg07/.rvm/gems/ruby-1.9.3-p125/gems/rspec-core-2.9.0/lib/rspec/core/example_group.rb:201:in `subclass' ...

知道我怎样才能完成这项工作吗?谢谢!

4

3 回答 3

0

您的模块不得包含在 Rails 自动加载路径中或不遵循自动加载约定。您可能只需在包含文件之前要求该文件即可解决此问题:

require 'spec_helper'
require './days'
describe Scheduler do
  include Days
于 2012-05-27T17:09:13.903 回答
0

Rails 4.1 有枚举。我刚刚升级并开始使用它。奇迹般有效!

http://edgeapi.rubyonrails.org/classes/ActiveRecord/Enum.html

于 2014-01-18T17:39:15.170 回答
0

ruby 没有枚举,但您可以在链接 http://www.rubyfleebie.com/enumerations-and-ruby/中执行类似的操作

于 2012-05-27T15:36:55.243 回答