0

Is there a concept of mock-objects in Inspec? I want to mock a REST API, because the server providing this API is not available in my build pipeline.

user5580578
  • 1,134
  • 1
  • 12
  • 28

1 Answers1

0

InSpec is built on top of RSpec, which is a popular testing library in Ruby. Fortunately, RSpec supports many forms of mocking, including Mocks and Stubs.

If you have some intermediate class that wraps this REST API functionality, say you call it ServiceGateway, then you can make a mock of that service in your InSpec tests with an RSpec double like so:

gateway = double('ServiceGateway')
expect(gateway).to receive(:get_data).and_return({ data: [1,2,3] })

# instantiate class under test providing the double to execute the rest of the test.

You should always check which version of RSpec the InSpec version you're using depends on. You can do this by looking at either your Gemfile.lock file or in RubyGems.org's transitive view. For example, InSpec 4.18.104 depends on RSpec 3.9.0 transitively through the inspec-core gem.

One final thought, if you're planning on interacting a bunch with REST APIs and want a more realistic representation of what they return for a more "end to end" style test (which InSpec ultimately is), consider pulling in the vcr gem. This gem performs record/playback of the API, making a real call the first time and using the saved results on subsequent tests. It does sometimes give you a false sense of security (it'll miss API changes), but it does give the full end to end experience.

Arthur Maltson
  • 5,760
  • 4
  • 30
  • 33
  • I thought that InSpec replaces RSpec. All RSpec tests should be replaced by using InSpec. – user5580578 Apr 19 '20 at 13:32
  • Yes, but InSpec is built on top of RSpec, it's a superset. Anything you can do in RSpec you can do in InSpec. – Arthur Maltson Apr 30 '20 at 13:12
  • To add further info to @ArthurMaltson 'superset' comment, Inspec adds extra resources that can be tested (cloud providers, os resources etc), and it adds metadata (impact, title, description, tags) which allow non-technical and/or governance users (such as CISO's) to understand the content. – Tricky Sep 05 '22 at 09:57