Rspec 未定义的方法 'describe'

Rspec undefined method 'describe'

我正在尝试完成教程,我感觉它与 rspec 有关。目标是让每个测试都通过。这是我可以做教程的网站,但我更喜欢在我自己的 mac 书中做。

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 hello_spec.rb。您应该使用 rspec 命令,而不是 ruby。有关详细信息,请参阅 https://relishapp.com/rspec/rspec-core/docs/command-line

这是代码:

# 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

You can use the ruby command to run specs. You just need to require rspec/autorun.Generally speaking, you're better off using the rspec command, which avoids the complexity of rspec/autorun (e.g. no at_exit hook needed!), but some tools only work with the ruby command.