要直接解决您的问题,您可以通过添加 RSpec 大大简化您的工作流程。 RSpec 是一个用于 Ruby 的 BDD(行为驱动开发)工具,它可以让您以一种(可以说)比简单的简单元测试更具描述性的方式来描述您的类。我在下面提供了一个小代码示例来帮助您入门。
如果您的项目没有 Gemfile,请创建一个 Gemfile 并添加 RSpec。如果您从未这样做过,请查看 Bundler 了解有关 Gemfile 的更多信息。
# in your Gemfile
gem 'rspec' # rspec testing tool
gem 'require_relative' # allows you to require files with relative paths
创建一个规范文件夹来存放你的规范(规范就是 RSpec 所说的测试)。
# via Command Line (or in Windows Explorer) create a spec folder in your project
mkdir spec
在 spec/ 文件夹中创建一个 spec_helper.rb 来存放您的测试配置。
# in spec/spec_helper.rb
require "rspec" # require rspec testing tool
require_relative '../tic_tac_toe' # require the class to be tested
config.before(:suite) do
begin
#=> code here will run before your entire suite
@first_player = Player.new
@second_player = Player.new
ensure
end
end
现在您已经在测试套件运行之前设置了两个播放器,您可以在测试中使用它们。为您想要测试的类创建一个规范并使用 _spec 作为后缀。
# in spec/player_spec.rb
require 'spec_helper' # require our setup file and rspec will setup our suite
describe Player do
before(:each) do
# runs before each test in this describe block
end
it "should have a name" do
# either of the bottom two will verify player's name is not nil, for example
@first_player.name.nil? == false
@first_player.name.should_not be_nil
end
end
使用 bundle exec rspec 从项目的根目录运行这些测试。这将寻找一个 spec/ 文件夹,加载 spec 助手,并运行你的 specs。您可以使用 RSpec 做更多事情,例如在工厂工作等(这将用于更大的项目)。但是,对于您的项目,您的课程只需要一些规范。
当您牢牢掌握 rspec 时,我建议的其他内容是 RSpec-Given。这个 gem 可以帮助你干掉你的 rspec 测试,让它们更具可读性。
您还可以查看 Guard 并创建一个 Guardfile,它会为您监视您的文件并在您更改文件时运行测试。
最后,我提出了一个关于基本项目结构的小建议,以便更容易地将其可视化。
/your_project
--- Gemfile
--- tic_tac_toe.rb
--- spec/
------- spec_helper.rb
------- player_spec.rb
我已经链接了所有引用的文档,所以如果您有任何问题,请务必查看链接。 Bundler、RSpec、RSpec-Given 和 Guard 的文档相当不错。快乐编程。