如何为此Rails自动加载错误编写测试用例

时间:2015-09-28 13:21:07

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

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

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作为此错误的正确解决方法?

1 个答案:

答案 0 :(得分:0)

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

让我们从一个有效的例子开始:

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
相关问题