如何在ruby中快速测试类行为

如何在ruby中快速测试类行为,ruby,testing,Ruby,Testing,我正在用Tic\u tac\u toe.rb中的所有类构建一个基于类的Tic-tac-toe游戏。我可以将类加载到irb中,以便使用irb-r./tic\u tac\u toe.rb进行交互测试,但每次我都必须手动创建一个播放器和gameboard实例。我包括了p1=Player.newinttic\u tac\u toe.rb,但它似乎没有运行 更一般地说,我正在做的工作流程是否良好?我应该如何着手为我的类编写一些代码,并对其进行测试和返回?(对于这个小项目,有没有比单元测试更简单的方法?为了

我正在用
Tic\u tac\u toe.rb
中的所有类构建一个基于类的Tic-tac-toe游戏。我可以将类加载到
irb
中,以便使用
irb-r./tic\u tac\u toe.rb
进行交互测试,但每次我都必须手动创建一个播放器和gameboard实例。我包括了
p1=Player.new
int
tic\u tac\u toe.rb
,但它似乎没有运行


更一般地说,我正在做的工作流程是否良好?我应该如何着手为我的类编写一些代码,并对其进行测试和返回?(对于这个小项目,有没有比单元测试更简单的方法?

为了直接解决您的问题,您可以通过添加RSpec大大简化您的工作流程。是一个用于Ruby的BDD(行为驱动开发)工具,它可以让您以一种(可以说)比普通单元测试更具描述性的方式来描述类。我在下面提供了一个小代码示例,以帮助您入门

如果您的项目没有GEM文件,请创建GEM文件并添加RSpec。如果您从未这样做过,请查看更多有关GEM文件的信息

# in your Gemfile
gem 'rspec'            # rspec testing tool
gem 'require_relative' # allows you to require files with relative paths
创建一个spec文件夹来存放您的spec(spec是RSpec所称的测试)

在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从项目的根目录运行这些测试。这将查找等级库/文件夹,加载等级库帮助程序,并运行等级库。使用RSpec,您可以做更多的事情,例如在工厂工作等(这将适用于更大的项目)。然而,对于您的项目,您只需要为您的类指定一些规范

我建议的其他事情是,当你牢牢掌握rspec时。这个gem有助于使您的rspec测试干涸,并使它们更具可读性

您还可以查看并创建一个Guardfile,它将为您监视文件,并在您更改文件时运行测试

最后,我对一个基本的项目结构提出了一个小小的建议,以便更容易地将其可视化

/your_project
--- Gemfile
--- tic_tac_toe.rb
--- spec/
------- spec_helper.rb
------- player_spec.rb  

我已经链接了所有被引用的文档,所以如果你有任何问题,一定要查看链接。关于Bundler、RSpec、RSpec和Guard的文档非常不错。快乐编程。

实际上,这似乎并不难设置。我要试试看!非常感谢你的详细回答
/your_project
--- Gemfile
--- tic_tac_toe.rb
--- spec/
------- spec_helper.rb
------- player_spec.rb