main:Object的未定义方法`before'

时间:2015-05-25 12:44:36

标签: ruby rspec serverspec

我从下面的代码部分得到了上述错误。原因是什么?

 1  require 'spec_helper'
 2
 3  before(:all) do
 4    puts "ServerSpec tests on #{ENV['TARGET_HOST']}"
 5  end

完整错误:

/home/newatson/src/serverspec/spec/cfengine3/common_spec.rb:3:in `<top (required)>': undefined method `before' for main:Object (NoMethodError)
        from /home/newatson/.gem/ruby/1.9.1/gems/rspec-core-3.2.3/lib/rspec/core/configuration.rb:1226:in `load'
        from /home/newatson/.gem/ruby/1.9.1/gems/rspec-core-3.2.3/lib/rspec/core/configuration.rb:1226:in `block in load_spec_files'
        from /home/newatson/.gem/ruby/1.9.1/gems/rspec-core-3.2.3/lib/rspec/core/configuration.rb:1224:in `each'
        from /home/newatson/.gem/ruby/1.9.1/gems/rspec-core-3.2.3/lib/rspec/core/configuration.rb:1224:in `load_spec_files'
        from /home/newatson/.gem/ruby/1.9.1/gems/rspec-core-3.2.3/lib/rspec/core/runner.rb:97:in `setup'
        from /home/newatson/.gem/ruby/1.9.1/gems/rspec-core-3.2.3/lib/rspec/core/runner.rb:85:in `run'
        from /home/newatson/.gem/ruby/1.9.1/gems/rspec-core-3.2.3/lib/rspec/core/runner.rb:70:in `run'
        from /home/newatson/.gem/ruby/1.9.1/gems/rspec-core-3.2.3/lib/rspec/core/runner.rb:38:in `invoke'
        from /home/newatson/.gem/ruby/1.9.1/gems/rspec-core-3.2.3/exe/rspec:4:in `<top (required)>'
        from /home/newatson/.gem/ruby/1.9.1/bin/rspec:19:in `load'
        from /home/newatson/.gem/ruby/1.9.1/bin/rspec:19:in `<main>'

2 个答案:

答案 0 :(得分:7)

before应在describe内实施:

require 'spec_helper'

describe "My Tests" do
  before(:all) do
    puts "ServerSpec tests on #{ENV['TARGET_HOST']}"
  end
end
祝你好运!

答案 1 :(得分:1)

好像你错过了描述你的课程。没有describe对象成为接收者,你有一个NoMethodError。轻松修复:

describe MyClass do
  before(:all) do
    #
  end
end