我正在使用 tic_tac_toe.rb
中的所有类构建一个基于类的井字游戏。我可以将类加载到 irb
以使用 irb -r ./tic_tac_toe.rb
进行交互式测试,但我每次都必须手动创建玩家和游戏板实例。我包含了 p1 = Player.new
int tic_tac_toe.rb
但它似乎没有运行。
更一般地说,我正在做的工作流程好不好?我应该如何为我的类(class)编写一些代码并对其进行测试并返回? (对于这个小项目,有没有比单元测试更简单的东西?)
最佳答案
要直接解决您的问题,您可以通过添加 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
创建一个 spec 文件夹来存放您的规范(规范是 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 helper,并运行你的 specs。你可以用 RSpec 做更多的事情,比如在工厂工作等(这适用于更大的项目)。但是,对于您的项目,您只需要为您的类(class)制定一些规范。
我建议的其他事情是 RSpec-Given ,当您牢牢掌握 rspec 时。这个 gem 有助于 DRY rspec 测试并使它们更具可读性。
您还可以查看 Guard并创建一个 Guardfile,它将为您监视您的文件并在您更改文件时运行测试。
最后,我提出了一个关于基本项目结构的小建议,以便更容易地形象化。
/your_project
--- Gemfile
--- tic_tac_toe.rb
--- spec/
------- spec_helper.rb
------- player_spec.rb
我已经链接了所有引用文档,所以如果您有任何问题,一定要查看这些链接。关于 Bundler、RSpec、RSpec-Given 和 Guard 的文档相当不错。快乐的编程。
关于ruby - 如何快速测试 ruby 中的类行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23533259/