我正在构建一个基于类的Tic-tac-toe游戏,其中包含tic_tac_toe.rb
中的所有类。我可以将类加载到irb
以进行irb -r ./tic_tac_toe.rb
的交互式测试,但我必须每次都手动创建一个播放器和游戏板实例。我包含p1 = Player.new
int tic_tac_toe.rb
,但似乎没有。
更一般地说,我是不是在做一个好的工作流程?我该如何为我的班级编写一些代码并进行测试并返回? (对于这个小项目,有没有比单元测试更简单的东西?)
答案 0 :(得分:1)
要直接解决您的问题,您可以通过添加RSpec大大简化您的工作流程。 RSpec是Ruby的BDD(行为驱动开发)工具,它允许您以(可以说)描述性方式描述您的类,而不是简单单元测试。我在下面添加了一个小代码示例,以帮助您入门。
如果您的项目没有Gemfile并添加RSpec,请创建一个Gemfile。如果您从未这样做,请查看Bundler以获取有关Gemfiles的更多信息。
# 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 /文件夹,加载规范帮助程序,并运行您的规范。您可以使用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的文档相当不错。快乐的节目。