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

Learning TTD Rspec. cant load require relative file

我正在尝试练习 TDD 和 rspec。我正在测试一种方法,该方法 returns 某个人的年龄来自出生年份的争论。 然而,当我 运行 rspec 它无法读取 require 相关文件。我不确定为什么。 我也想知道我是否做错了什么。谢谢。

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

您想要的文件在一个目录上,但随后嵌套在 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 中确实没有任何内容,但这应该是您的典型文件结构。