学习TTD Rspec。无法加载需要相关文件

时间:2018-10-31 18:28:21

标签: ruby rspec tdd

我试图练习TDD和rspec。我正在测试一种方法,该方法可以根据出生年份的参数返回某人的年龄。 但是,当我运行rspec时,它无法读取所需的相对文件。我不确定为什么。 我也想知道我是否做错了其他任何事情。谢谢。

require "date"
def current_age_for_birth_year(birthyear)
  year = Date.today.year
  puts birthyear - year
end

require_relative '../current_age_for_birth_year'

describe "current_age_for_birth_year method" do
  it "returns the age of a person based on the year of birth" do
    age_of_person = current_age_for_birth_year(1984)

    expect(age_of_person).to eq(19)
  end
end

source 'https://rubygems.org'
gem "rspec"

  testing rspec

An error occurred while loading ./spec/current_age_for_birth_year_spec.rb.
Failure/Error: require_relative 'current_age_for_birth_year'

LoadError:
  cannot load such file -- /Users/benherring/testing/spec/current_age_for_birth_year
# ./spec/current_age_for_birth_year_spec.rb:1:in `require_relative'
# ./spec/current_age_for_birth_year_spec.rb:1:in `<top (required)>'
No examples found.

Finished in 0.00027 seconds (files took 0.10919 seconds to load)
0 examples, 0 failures, 1 error occurred outside of examples

enter image description here

1 个答案:

答案 0 :(得分:0)

您想要的文件位于一个目录中,但随后将其嵌套在app文件夹中,因此,请尝试使用此文件

require_relative '../app/current_age_for_birth_year'

在旁注中,看起来您是在spec文件夹中创建了Gemfile,但是通常您希望将Gemfile保留在项目文件夹的根目录中,因此在这种情况下,您可能希望移动

test/spec/Gemfile
test/spec/Gemfile.lock

上一级:

test/Gemfile
test/Gemfile.lock

从外观上看,您的Gemfile中实际上没有任何东西,但这应该是您的典型文件结构。