【问题标题】:Rspec undefined method 'describe'Rspec未定义的方法“描述”
【发布时间】:2015-01-24 18:06:56
【问题描述】:

我正在尝试阅读本教程,但我感觉这与 rspec 有关。目标是使每个测试通过。这是我可以做教程的网站,但我更喜欢在我自己的 mac book 上做。

http://testfirst.org/live

https://web.archive.org/web/20140328135623/http://testfirst.org/learn_ruby

我是第一个,每次我都跑

$ruby hello_spec.rb

我收到此错误。

hello_spec.rb:118:in `<main>': undefined method `describe' for main:Object (NoMethodError)

rspec (3.1.0, 2.99.0, 2.14.1)

ruby 2.0.0p481(2014-05-08 修订版 45883)[x86_64-darwin14.0.0]

require_relative "hello"
describe "the hello function" do
  it "says hello" do
    hello.should == "Hello!"
  end
end

describe "the greet function" do
  it "says hello to someone" do
    greet("Alice").should == "Hello, Alice!"
  end

  it "says hello to someone else" do
    greet("Bob").should == "Hello, Bob!"
  end
end

请帮忙!

【问题讨论】:

  • 您需要向我们展示您正在运行的代码。您是否安装了rspec 并且在该文件中需要它?默认不安装
  • 请给代码...

标签: ruby-on-rails ruby rspec


【解决方案1】:

代码如下:

# hello.rb
#!/usr/bin/env ruby

def greet(name)
  "Hello, #{name}!"
end

def hello
  "Hello!"
end

#hello_spec.rb
require_relative "../hello.rb"

describe "the hello function" do
  it "says hello" do
    expect(hello).to eq "Hello!"
  end
end

describe "the greet function" do
  it "says hello to someone" do
    expect(greet("Alice")).to eq("Hello, Alice!")
  end

  it "says hello to someone else" do
    expect(greet("Bob")).to eq("Hello, Bob!")
  end
end

现在我使用rubyrspec 命令运行:

[arup@Ruby]$ rspec spec/test_spec.rb
...

Finished in 0.00153 seconds (files took 0.12845 seconds to load)
3 examples, 0 failures
[arup@Ruby]$ ruby spec/test_spec.rb
spec/test_spec.rb:3:in `<main>': undefined method `describe' for main:Object (NoMethodError)
[arup@Ruby]$

这意味着,通过此设置,您需要使用rspec 命令运行该文件。但是,如果您想使用ruby 命令,则需要将您的文件设置如下:

require_relative "../hello.rb"
require 'rspec/autorun'

RSpec.describe "the hello function" do
  it "says hello" do
    expect(hello).to eq "Hello!"
  end
end

RSpec.describe "the greet function" do
  it "says hello to someone" do
    expect(greet("Alice")).to eq("Hello, Alice!")
  end

  it "says hello to someone else" do
    expect(greet("Bob")).to eq("Hello, Bob!")
  end
end

然后运行:

[arup@Ruby]$ ruby spec/test_spec.rb
...

Finished in 0.00166 seconds (files took 0.15608 seconds to load)
3 examples, 0 failures
[arup@Ruby]$

Run with ruby command

您可以使用 ruby​​ 命令运行规范。你只需要require rspec/autorun。一般来说,你最好使用rspec命令,这避免了rspec/autorun的复杂性(例如不需要at_exit钩子!),但有些工具只适用于ruby命令。

【讨论】:

    【解决方案2】:

    试试rspec hello_spec.rb。您应该使用 rspec 命令,而不是 ruby​​。详情请见https://relishapp.com/rspec/rspec-core/docs/command-line

    【讨论】:

    • 您也可以使用ruby 命令,但需要做一些额外的工作。问题出在其他地方。
    猜你喜欢
    • 2015-01-15
    • 2018-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多