【问题标题】:How to write a test case for this Rails autoload error如何为此 Rails 自动加载错误编写测试用例
【发布时间】:2015-09-28 13:21:07
【问题描述】:

我在app/models/foo.rb 中定义了一个模型Foo

class Foo
  def self.bar
    # do bar
  end
end

app/use_cases/do_bar.rb中定义的用例中调用此方法

module UseCases
  class DoBar
    def call
      Foo.bar
    end
  end
end

最近,我遇到了以下空气制动错误:

UseCases::Foo:Class 的未定义方法 `bar'

我假设这个错误可以通过在用例中添加::Foo 来解决,但我不确定如何强制这个错误?我已经进行了用例测试,无论是否使用::,这些测试都通过了。

如何编写测试以确保将:: 前置到Foo 是解决此错误的正确方法?

【问题讨论】:

  • 你真的有 UseCases::Foo 吗?
  • @violarium,这是一个合理的问题:P 不,我不知道。
  • 但是很奇怪,如果不这样做,就会出现类似“NameError: uninitialized constant UseCases”这样的错误

标签: ruby-on-rails ruby ruby-on-rails-4 rspec


【解决方案1】:

每当在DoBar 类的模块层次结构中向下定义类Foo 时,此错误似乎是可重现的。

让我们从一个工作示例开始:

class Foo
  def self.bar
    p 'bar'
  end
end

module UseCases
  class DoBar
    def call
      Foo.bar
    end
  end
end

UseCases::DoBar.new.call #=> bar

我们可以通过添加以下类来重现undefined method 'bar' 异常:

module UseCases
  class Foo
  end
end

虽然在与DoBar 相同的模块中,但UseCases::Foo 类优先于::Foo 类。如果我们将UseCases::Foo 移到更深的层次结构中,我们的异常就会消失:

# having UseCases::OneMore::Foo doesn't cause any problems
module UseCases
  module OneMore
    class Foo
    end
  end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-03
    • 1970-01-01
    • 1970-01-01
    • 2014-03-22
    • 2016-02-14
    • 2011-09-08
    • 1970-01-01
    相关资源
    最近更新 更多