RSpec NoMethodError:"主要对象的未定义方法`描述"

Bor*_*yev 27 ruby rspec

我正在努力学习Rspec.我在Eclipse中的ruby项目如下 -

在此输入图像描述

代码-

require 'rspec'
require './RubyOffRailsTuts/classes/furlong'

describe Furlong do
end
Run Code Online (Sandbox Code Playgroud)

错误-

/RubyOffRailsTuts/specs/furlong_spec.rb:6:in `<main>': undefined 
method `describe' for main:Object (NoMethodError)
Run Code Online (Sandbox Code Playgroud)

没有在线获得任何有用的答案.我该如何解决这个问题?

0xt*_*bit 38

替代作序describeRSpec.describe,你可以添加

config.expose_dsl_globally = true
Run Code Online (Sandbox Code Playgroud)

到你的spec_helper.rb.

  • 仅当放在 `config.disable_monkey_patching!` 之后才有效,如果该行未注释 (5认同)

use*_*951 28

根本问题是基本对象main没有describe方法,除非你给它一个,这反映在错误消息" 主要对象的未定义方法describe ".

另外,我可以想到两种方法来解决这个问题:

1)打电话RSpec.describe而不是公正describe

require 'rspec'
require './RubyOffRailsTuts/classes/furlong'

RSpec.describe Furlong do
end
Run Code Online (Sandbox Code Playgroud)

2)调用include RSpec,使describe提供给main

require 'rspec'
require './RubyOffRailsTuts/classes/furlong'

include RSpec

describe Furlong do
end
Run Code Online (Sandbox Code Playgroud)


sev*_*cat 20

你的前缀describeRSpec,例如.RSpec.describe因为听起来你正在使用RSpec的现代版本来禁用猴子修补.


Tyl*_*ier 17

我同意sevenseacat你可能会使用现代版本的RSpec禁用猴子修补.

默认情况下,spec_helper.rb当您执行类似操作时创建文件时,将禁用此禁用

$ rails generate rspec:install
Run Code Online (Sandbox Code Playgroud)

spec_helper.rb,你会看到一个看起来像这样的部分:

# Limits the available syntax to the non-monkey patched syntax that is
# recommended. For more details, see:
#   - http://myronmars.to/n/dev-blog/2012/06/rspecs-new-expectation-syntax
#   - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/
#   - http://myronmars.to/n/dev-blog/2014/05/notable-changes-in-rspec-3#new__config_option_to_disable_rspeccore_monkey_patching
config.disable_monkey_patching!
Run Code Online (Sandbox Code Playgroud)

你可以注释掉最后一行.

但是,推荐的方法是不使用猴子修补和使用RSpec.describe.