我试图通过教程,我感觉它与rspec有关。目标是让每个测试通过。这是我可以在这里做教程的网站,但我更喜欢在我自己的Mac书上做。
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
请帮忙!
答案 0 :(得分: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
现在我使用ruby
和rspec
命令运行:
[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]$
您可以使用ruby命令运行规范。您只需要
require rspec/autorun
。一般来说,您最好使用rspec命令,这样可以避免rspec/autorun
的复杂性(例如,不需要at_exit
挂钩!),但有些工具仅适用于ruby
命令。
答案 1 :(得分:0)
试试rspec hello_spec.rb
。你应该使用rspec命令,而不是ruby。有关详细信息,请参阅https://relishapp.com/rspec/rspec-core/docs/command-line。