【问题标题】:How to call module in Ruby rspec?如何在 Ruby rspec 中调用模块?
【发布时间】:2014-04-11 09:50:38
【问题描述】:

lib/rspec/core/my_methods.rb

module MyLovelyModule

class My_methods

  def my_lovely_method
    save_world

    config.to_prepare do
      Dir.glob(Rails.root + "../simpleRspec/dummy_classes.rb").each do |c|
        require_dependency(c)
      end
  end
end
end
  end

lib/simpleRspec/dummy_classes.rb

describe MyLovelyModule do

class DummyClasses

  before(:all) do
    @dummy = DummyClasses.new
    @dummy.extend MyLovelyModule
  end

  describe "MyLovelyModule" do
    it "saves the world" do
      expect {
        @dummy.my_lovely_method
      }.to raise_error MeltDownException
    end
  end
end
end

我遇到了这样的错误:-

C:/Users/afzala/RubymineProjects/simpleRspec/lib/simpleRspec/dummy_classes.rb:2:in `<top (required)>': uninitialized constant MyLovelyModule (NameError)
    from -e:1:in `load'
    from -e:1:in `<main>'

Process finished with exit code 1

谁能帮我解决这个问题

【问题讨论】:

  • 你有 spec_helper.rb 文件吗?你也可以展示一下吗?是 Rails 应用吗?

标签: ruby selenium rspec


【解决方案1】:

您需要先加载您的模块。您还需要在定义测试之前关闭该类:

require 'lib/rspec/core/my_methods.rb'

describe MyLovelyModule do

  class DummyClasses
  end

  before(:all) do
    @dummy = DummyClasses.new
    @dummy.extend MyLovelyModule
  end

  describe "MyLovelyModule" do
    it "saves the world" do
      expect {
        @dummy.my_lovely_method
      }.to raise_error MeltDownException
    end
  end
end

此外,您将无法在测试中访问@dummy。您需要使用before(:each) 代替before(:all)

【讨论】:

  • 我收到此错误加载错误.... C:/Users/afzala/RubymineProjects/simpleRspec/lib/simpleRspec/dummy_classes.rb:1:in require': cannot load such file -- lib/rspec/core/my_methods.rb (LoadError) from C:/Users/afzala/RubymineProjects/simpleRspec/lib/simpleRspec/dummy_classes.rb:1:in ' from -e:1:in load' from -e:1:in
    ' 进程以退出代码 1 结束
  • 正如预期的那样。它是 Rails 应用程序,您的加载路径中有什么?为什么将应用模块存储在名为“rspec”的文件夹中?
  • 不是 gem 应用程序
  • 你有spec_helper.rb文件吗?
  • 是的,在我的 spec_helper.rb 中,RSpec.configure do |config| 下面给出# config.before(:each) {print ('before method')} config.before(:each)do end config.after(:each)do end config.before(:all)do end config.after(:all )do config.before(:suite)do end config.after(:suite)do end end end
猜你喜欢
  • 1970-01-01
  • 2017-07-24
  • 1970-01-01
  • 2013-04-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-27
  • 1970-01-01
相关资源
最近更新 更多