【问题标题】:How to use RSpec without Rails?如何在没有 Rails 的情况下使用 RSpec?
【发布时间】:2012-08-31 16:30:03
【问题描述】:

在没有 Rails 的情况下使用 RSpec 在 Ruby 中进行 TDD 的过程是什么?

我需要 Gemfile 吗?里面只需要rspec吗?

Ruby 1.9.3

【问题讨论】:

  • 我认为它与没有它几乎相同,因为 rails 和 rspec 之间没有直接连接。
  • 从页面的标题和视频的标题上看有点难,但这似乎适用于 Rails 和无 Rails 的 Ruby 项目。

标签: ruby rspec tdd bdd


【解决方案1】:

gem install rspec 周围的工作流程存在缺陷。始终使用 Bundler 和 Gemfile 来确保一致性并避免项目在一台计算机上正常运行但在另一台计算机上失败的情况。

创建您的Gemfile

source 'https://rubygems.org/'

gem 'rspec'

然后执行:

gem install bundler
bundle install
bundle exec rspec --init

上面将为你创建.rspecspec/spec_helpers.rb

现在在spec/example_spec.rb 中创建您的示例规范:

describe 'ExampleSpec' do
  it 'is true' do
    expect(true).to be true
  end
end

然后运行规范:

% bundle exec rspec
.

Finished in 0.00325 seconds (files took 0.09777 seconds to load)
1 example, 0 failures

【讨论】:

  • 这是有道理的,可能是最佳实践。但是,它也假设在这里使用 rspec 的目的是自动开源和/或共享项目。对于您只想使用 rspec 对用户脚本进行本地测试的情况,这可能是矫枉过正。
  • 我几乎不会将那几行称为“矫枉过正”,并建议任何人使用 bundler,如这个出色的答案所示!
【解决方案2】:

流程如下:

从控制台安装 rspec gem:

gem install rspec

然后创建一个包含以下内容的文件夹(我们将其命名为 root):

root/my_model.rb

root/spec/my_model_spec.rb

#my_model.rb
class MyModel
  def the_truth
    true
  end
end

#spec/my_model_spec.rb

require_relative '../my_model'

describe MyModel do
  it "should be true" do
    MyModel.new.the_truth.should be_true
  end
end

然后在控制台运行

rspec spec/my_model_spec.rb

瞧!

【讨论】:

    【解决方案3】:

    从您的项目目录中...

    gem install rspec
    rspec --init
    

    然后在创建的规范目录中写入规范并通过

    运行它们
    rspec 'path to spec' # or just rspec to run them all
    

    【讨论】:

      猜你喜欢
      • 2014-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多