Skip to content

Instantly share code, notes, and snippets.

@bytheway
Last active January 4, 2016 20:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bytheway/8672304 to your computer and use it in GitHub Desktop.
Save bytheway/8672304 to your computer and use it in GitHub Desktop.
Using more of the build-in goodness chefspec provides to simplify things even further. We can run expectations against the chef runner directly.
# I wanted to find a way to unit test a "Heavy-Weight" provider, but all the examples I found ended up stubbing out
# the chef world to make sure we could verify functionality as well as prevent the provider from converging on the
# development machine.
#
# I started thinking that chefspec already isolates things, and provides a great suite of matchers that we can
# use to check on the creation of chef resources inside our heavy provider. This is one approach that allows
# testing a single provider method, without a full chef run, in "isolation," with the helpful chefspec matchers.
# In my spec_helper
class ChefSpec::UnitRunner < ChefSpec::Runner
def step_into?(*args)
false
end
def compiling?
false
end
def run_context
@run_context ||= Chef::RunContext.new(node, {}, Chef::EventDispatch::Dispatcher.new)
end
end
# Provider Spec
subject(:provider) do
Chef::Provider::MyProvider.new(resource, runner.run_context).tap do |p|
p.load_current_resource
end
end
let(:runner) do
ChefSpec::UnitRunner.new do |node|
node.automatic['platform'] = 'redhat'
node.automatic['platform_version'] = '6.4'
node.automatic['fqdn'] = 'rspec-host'
node.automatic['hostname'] = 'rspec-host'
end
end
let(:resource) do
Chef::Resource::MyResource.new("resourcename").tap do |r|
r.attribute_one "value"
end
end
it "creates the basic config files" do
provider.create_base_templates
expect(runner).to create_template("/etc/my-settings.conf")
end
# Provider method
def create_base_templates
template "/etc/my-settings.conf" do
mode 0644
end.run_action(:create)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment