Setup RSpec to test a gem (not Rails)

后端 未结 4 848
野趣味
野趣味 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:16

    Here's a cheap and easy (though not officially recommended) way:

    Make a dir in your gem's root called spec, put your specs in there. You probably already have rspec installed, but if you don't, just do a gem install rspec and forget Gemfiles and bundler.

    Next, you'll make a spec, and you need to tell it where your app is, where your files are, and include the file you want to test (along with any dependencies it has):

    # spec/awesome_gem/awesome.rb
    APP_ROOT = File.expand_path(File.join(File.dirname(__FILE__), '..', '..'))
    $: << File.join(APP_ROOT, 'lib/awesome_gem') # so rspec knows where your file could be
    require 'some_file_in_the_above_dir' # this loads the class you want to test
    
    describe AwesomeGem::Awesome do
      before do
        @dog = AwesomeGem::Awesome.new(name: 'woofer!')
      end
      it 'should have a name' do
        @dog.name.should eq 'woofer!'
      end
      context '#lick_things' do
        it 'should return the dog\'s name in a string' do
          @dog.lick_things.should include 'woofer!:'
        end
      end
    end
    

    Open up Terminal and run rspec:

    ~/awesome_gem $ rspec
    ..
    
    Finished in 0.56 seconds
    2 examples, 0 failures
    

    If you want some .rspec options love, go make a .rspec file and put it in your gem's root path. Mine looks like this:

    # .rspec
    --format documentation --color --debug --fail-fast
    

    Easy, fast, neat!

    I like this because you don't have to add any dependencies to your project at all, and the whole thing remains very fast. bundle exec slows things down a little, which is what you'd have to do to make sure you're using the same version of rspec all the time. That 0.56 seconds it took to run two tests was 99% taken up by the time it took my computer to load up rspec. Running hundreds of specs should be extremely fast. The only issue you could run into that I'm aware of is if you change versions of rspec and the new version isn't backwards compatible with some function you used in your test, you might have to re-write some tests.

    This is nice if you are doing one-off specs or have some good reason to NOT include rspec in your gemspec, however it's not very good for enabling sharing or enforcing compatibility.

提交回复
热议问题