Setup RSpec to test a gem (not Rails)

后端 未结 4 859
野趣味
野趣味 2020-12-07 06:52

It is pretty easy with the added generator of rspec-rails to setup RSpec for testing a Rails application. But how about adding RSpec for testing a gem in development? I am n

4条回答
  •  悲哀的现实
    2020-12-07 07:35

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

    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
    

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

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

    spec.add_development_dependency "rspec"
    

    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
    

    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.

    Create a spec, for example spec/foobar_spec.rb:

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

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

    --color
    --format documentation
    

    Finally: run the specs:

    $ rspec spec/foobar_spec.rb
    

提交回复
热议问题