设置 RSpec 来测试 gem(不是 Rails) [英] Set up RSpec to test a gem (not Rails)

查看:35
本文介绍了设置 RSpec 来测试 gem(不是 Rails)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用添加的 rspec-rails 生成器设置 RSpec 以测试 Rails 应用程序非常容易.但是如何添加 RSpec 来测试开发中的 gem 呢?我没有使用珠宝商或此类工具.我只是使用 Bundler (bundle gem my_gem) 来设置新 gem 的结构并手动编辑 *.gemspec.我还在 gemspec 中添加了 s.add_development_dependency "rspec", ">= 2.0.0" 并做了一个 bundle install.

It is pretty easy with the added generator of rspec-rails to set up RSpec for testing a Rails application. But how about adding RSpec for testing a gem in development? I am not using jeweler or such tools. I just used Bundler (bundle gem my_gem) to setup the structure for the new gem and edit the *.gemspec manually. I also added s.add_development_dependency "rspec", ">= 2.0.0" to gemspec and did a bundle install.

是否有一些不错的教程接下来要做什么才能使 RSpec 工作?

Is there some nice tutorial what to do next to get RSpec working?

推荐答案

我已经更新了这个答案以匹配当前的最佳实践:

I've updated this answer to match current best practices:

Bundler 完美支持 gem 开发.如果您要创建 gem,则您的 Gemfile 中唯一需要的内容如下:

Bundler supports gem development perfectly. If you are creating a gem, the only thing you need to have in your Gemfile is the following:

source "https://rubygems.org"
gemspec

这会告诉 Bundler 在您运行 bundle install 时查看您的 gemspec 文件中的依赖项.

This tells Bundler to look inside your gemspec file for the dependencies when you run bundle install.

接下来,确保 RSpec 是您的 gem 的开发依赖项.编辑 gemspec 使其显示为:

Next up, make sure that RSpec is a development dependency of your gem. Edit the gemspec so it reads:

spec.add_development_dependency "rspec"

接下来,创建 spec/spec_helper.rb 并添加如下内容:

Next, create spec/spec_helper.rb and add something like:

require 'bundler/setup'
Bundler.setup

require 'your_gem_name' # and any other gems you need

RSpec.configure do |config|
  # some (optional) config here
end

前两行告诉 Bundler 只加载 gemspec 中的 gem.当您在自己的机器上安装自己的 gem 时,这将强制您的规范使用您当前的代码,而不是您单独安装的版本.

The first two lines tell Bundler to load only the gems inside your gemspec. When you install your own gem on your own machine, this will force your specs to use your current code, not the version you have installed separately.

创建一个规范,例如spec/foobar_spec.rb:

require 'spec_helper'
describe Foobar do
  pending "write it"
end

可选:为默认选项添加一个 .rspec 文件并将其放在您的 gem 的根路径中:

Optional: add a .rspec file for default options and put it in your gem's root path:

--color
--format documentation

最后:运行规范:

$ rspec spec/foobar_spec.rb

这篇关于设置 RSpec 来测试 gem(不是 Rails)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆