【问题标题】:How to quickly test Class behavior in ruby如何在 ruby​​ 中快速测试类行为
【发布时间】:2014-05-08 05:16:16
【问题描述】:

我正在构建一个基于类的井字游戏,其中包含tic_tac_toe.rb 中的所有类。我可以将类加载到irb 以使用irb -r ./tic_tac_toe.rb 进行交互式测试,但我每次都必须手动创建玩家和游戏板实例。我包括了p1 = Player.new int tic_tac_toe.rb,但这似乎没有运行。

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

【问题讨论】:

    标签: ruby testing


    【解决方案1】:

    要直接解决您的问题,您可以通过添加 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 的文档相当不错。快乐编程。

    【讨论】:

    • 这实际上似乎并不难设置。我会试试看!非常感谢您的详细解答
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-30
    • 2021-08-03
    • 1970-01-01
    相关资源
    最近更新 更多