How to write regression tests for custom Chef resources? - ruby

Given the minimal example
# resources/novowel.rb
resource_name :novowel
property :name, String, name_property: true, regex: /\A[^aeiou]\z/
I would like to write the unit tests in spec/unit/resources/novowel_spec.rb
Resource 'novowel' for name should accept 'k'
Resource 'novowel' for name should accept '&'
Resource 'novowel' for name should NOT accept 'a'
Resource 'novowel' for name should NOT accept 'mm'
to ensure that the name property still works correctly even if the regex is changed for some reason.
I browsed several top notch Chef cookbooks but could not find references for such testing.
How can it be done? Feel free to provide more complex examples with explicitly subclassing Chef::Resource if that helps achieve the task.
Update 1: Could it be that Chef does NOT FAIL when a property does not fit the regex? Clearly this should not work:
link '/none' do
owner 'r<oo=t'
to '/usr'
end
but chef-apply (12.13.37) does not complain about r<oo=t not matching owner_valid_regex. It simply converges as if owner would not have been provided.

You would use ChefSpec and RSpec. I've got examples in all of my cookbooks (ex. https://github.com/poise/poise-python/tree/master/test/spec/resources) but I also use a bunch of custom helpers on top of plain ChefSpec so it might not be super helpful. Doing in-line recipe code blocks in the specs makes it waaaay easier. I've started extracting my helpers out for external use in https://github.com/poise/poise-spec but it's not finished. The current helpers are in my Halite gem, see the readme there for more info.

We wrap the DSL inside a little Ruby in order to know the name of the resource's Ruby class:
# libraries/no_vowel_resource.rb
require 'chef/resource'
class Chef
class Resource
class NoVowel < Chef::Resource
resource_name :novowel
property :letter, String, name_property: true, regex: /\A[^aeiou]\z/
property :author, String, regex: /\A[^aeiou]+\z/
end
end
end
and now we can use RSpec with
# spec/unit/libraries/no_vowel_resource_spec.rb
require 'spec_helper'
require_relative '../../../libraries/no_vowel_resource.rb'
describe Chef::Resource::NoVowel do
before(:each) do
#resource = described_class.new('k')
end
describe "property 'letter'" do
it "should accept the letter 'k'" do
#resource.letter = 'k'
expect(#resource.letter).to eq('k')
end
it "should accept the character '&'" do
#resource.letter = '&'
expect(#resource.letter).to eq('&')
end
it "should NOT accept the vowel 'a'" do
expect { #resource.letter = 'a' }.to raise_error(Chef::Exceptions::ValidationFailed)
end
it "should NOT accept the word 'mm'" do
expect { #resource.letter = 'mm' }.to raise_error(Chef::Exceptions::ValidationFailed)
end
end
describe "property 'author'" do
it "should accept a String without vowels" do
#resource.author = 'cdrngr'
expect(#resource.author).to eq('cdrngr')
end
it "should NOT accept a String with vowels" do
expect { #resource.author = 'coderanger' }.to raise_error(Chef::Exceptions::ValidationFailed)
end
end
end

Related

Can I use a built-in RSpec matcher in a custom matcher?

I have the following expectation in a feature spec (pretty low-level but still necessary):
expect(Addressable::URI.parse(current_url).query_values).to include(
'some => 'value',
'some_other' => String
)
Note the second query value is a fuzzy match because I just want to make sure it's there but I can't be more specific about it.
I'd like to extract this into a custom matcher. I started with:
RSpec::Matchers.define :have_query_params do |expected_params|
match do |url|
Addressable::URI.parse(url).query_values == expected_params
end
end
but this means I cannot pass {'some_other' => String} in there. To keep using a fuzzy match, I'd have to use the include matcher in my custom matcher.
However, anything within RSpec::Matchers::BuiltIn is marked as private API, and Include specifically is documented as:
# Provides the implementation for `include`.
# Not intended to be instantiated directly.
So, my question is: Is using a built-in matcher within a custom matcher supported in RSpec? How would I do that?
RSpec::Matchers appears to be a supported API (its rdoc doesn't say otherwise), so you can write your matcher in Ruby instead of in the matcher DSL (which is supported; see the second paragraph of the custom matcher documentation) and use RSpec::Matchers#include like this:
spec/support/matchers.rb
module My
module Matchers
def have_query_params(expected)
HasQueryParams.new expected
end
class HasQueryParams
include RSpec::Matchers
def initialize(expected)
#expected = expected
end
def matches?(url)
actual = Addressable::URI.parse(url).query_values
#matcher = include #expected
#matcher.matches? actual
end
def failure_message
#matcher.failure_message
end
end
end
end
spec/support/matcher_spec.rb
include My::Matchers
describe My::Matchers::HasQueryParams do
it "matches" do
expect("http://example.com?a=1&b=2").to have_query_params('a' => '1', 'b' => '2')
end
end
Yes, you can call built-in rspec matchers from within a custom matcher. Put another way, you can use the normal Rspec DSL instead of pure Ruby when writing your matcher. Check out this gist (not my gist, but it helped me!).
I've got a really complex controller with a tabbed interface where the defined and selected tab depend on the state of the model instance. I needed to test tab setup in every state of the :new, :create, :edit and :update actions. So I wrote these matchers:
require "rspec/expectations"
RSpec::Matchers.define :define_the_review_tabs do
match do
expect(assigns(:roles )).to be_a_kind_of(Array)
expect(assigns(:creators )).to be_a_kind_of(ActiveRecord::Relation)
expect(assigns(:works )).to be_a_kind_of(Array)
expect(assigns(:available_tabs)).to include("post-new-work")
expect(assigns(:available_tabs)).to include("post-choose-work")
end
match_when_negated do
expect(assigns(:roles )).to_not be_a_kind_of(Array)
expect(assigns(:creators )).to_not be_a_kind_of(ActiveRecord::Relation)
expect(assigns(:works )).to_not be_a_kind_of(Array)
expect(assigns(:available_tabs)).to_not include("post-new-work")
expect(assigns(:available_tabs)).to_not include("post-choose-work")
end
failure_message do
"expected to set up the review tabs, but did not"
end
failure_message_when_negated do
"expected not to set up review tabs, but they did"
end
end
RSpec::Matchers.define :define_the_standalone_tab do
match do
expect(assigns(:available_tabs)).to include("post-standalone")
end
match_when_negated do
expect(assigns(:available_tabs)).to_not include("post-standalone")
end
failure_message do
"expected to set up the standalone tab, but did not"
end
failure_message_when_negated do
"expected not to set up standalone tab, but they did"
end
end
RSpec::Matchers.define :define_only_the_review_tabs do
match do
expect(assigns).to define_the_review_tabs
expect(assigns).to_not define_the_standalone_tab
expect(assigns(:selected_tab)).to eq(#selected) if #selected
end
chain :and_select do |selected|
#selected = selected
end
failure_message do
if #selected
"expected to set up only the review tabs and select #{#selected}, but did not"
else
"expected to set up only the review tabs, but did not"
end
end
end
RSpec::Matchers.define :define_only_the_standalone_tab do
match do
expect(assigns).to define_the_standalone_tab
expect(assigns).to_not define_the_review_tabs
expect(assigns(:selected_tab)).to eq("post-standalone")
end
failure_message do
"expected to set up only the standalone tab, but did not"
end
end
RSpec::Matchers.define :define_all_tabs do
match do
expect(assigns).to define_the_review_tabs
expect(assigns).to define_the_standalone_tab
expect(assigns(:selected_tab)).to eq(#selected) if #selected
end
chain :and_select do |selected|
#selected = selected
end
failure_message do
if #selected
"expected to set up all three tabs and select #{#selected}, but did not"
else
"expected to set up all three tabs, but did not"
end
end
end
And am using them like so:
should define_all_tabs.and_select("post-choose-work")
should define_all_tabs.and_select("post-standalone")
should define_only_the_standalone_tab
should define_only_the_review_tabs.and_select("post-choose-work")
should define_only_the_review_tabs.and_select("post-new-work")
Super-awesome to be able to just take several chunks of repeated expectations and roll them up into a set of custom matchers without having to write the matchers in pure Ruby.
This saves me dozens of lines of code, makes my tests more expressive, and allows me to change things in one place if the logic for populating these tabs changes.
Also note that you have access in your custom matcher to methods/variables such as assigns and controller so you don't need to pass them in explicitly.
Finally, I could have defined these matchers inline in the spec, but I chose to put them in spec/support/matchers/controllers/posts_controller_matchers.rb
You can use the matcher DSL instead of writing your own Matcher class. It is a bit simpler.
RSpec::Matchers.define :have_query_params do |expected|
match do |actual|
# your code
RSpec::Matchers::BuiltIn::Include.new(expected).matches?(actual)
end
end

How do I search a YAML file?

I have a YAML file books.yaml:
- !ruby.object:Book
title: Ruby for Newbz
author: LeeRoy Jenkins
category: Educational
I already have a method that adds books to this file, but I need a method that can search the YAML file using a regular expression. If no book matches the title then it should raise an exception NoBookfound. If there are any matches, that list should be returned to the caller.
Here is my existing code:
require 'yaml'
require './book'
class Library
attr_accessor :books
def initialize file_name = false
#books = file_name ? YAML::load(File.read(file_name)) : []
end
def add_book(book)
#books.push(book)
end
def search_library(file_name , book)
if
YAML::load(File.read(file_name)).include?(book) == false
raise 'No Book Found'
end
end
end
This is something I tried for the exception portion, but I feel like I'm way off. I'm really new to Ruby and this seems to be a pretty hard task. Does anyone have any ideas?
What you need is to test the class from the loaded object:
book = YAML::load(File.read(file_name))
raise 'No Book Found' unless book.kind_of? Book
There are also some kind_of? alternatives, which you can read about the differences on this nice question
Based on your post, I guess that book param is a Regexp object.
I think you should remove the file_name param from search method, since the file is already loaded on initialize method.
My implemetation would be:
def search_library term
#books.find_all {|b| b.title =~ term}
end
Since you already have "#books" in an enumerable you can use the select method to find books whose title have the search term as a substring.
def search_library(term)
matches = #books.select { |x| x.title.index(term) }
raise "No books have title like '#{term}'" if matches.empty?
matches
end

Minitest spec custom matcher

I have a line in my test:
page.has_reply?("my reply").must_equal true
and to make it more readable I want to use a custom matcher:
page.must_have_reply "my reply"
Based on the docs for https://github.com/zenspider/minitest-matchers I expect I need to write a matcher which looks something like this:
def have_reply(text)
subject.has_css?('.comment_body', :text => text)
end
MiniTest::Unit::TestCase.register_matcher :have_reply, :have_reply
The problem is that I can't see how to get a reference to the subject (i.e. the page object). The docs say "Note subject must be the first argument in assertion" but that doesn't really help.
There is a little example, you can create a class which should responds to set of methods matches?, failure_message_for_should, failure_message_for_should_not.
In matches? method you can get the reference to the subject.
class MyMatcher
def initialize(text)
#text = text
end
def matches? subject
subject =~ /^#{#text}.*/
end
def failure_message_for_should
"expected to start with #{#text}"
end
def failure_message_for_should_not
"expected not to start with #{#text}"
end
end
def start_with(text)
MyMatcher.new(text)
end
MiniTest::Unit::TestCase.register_matcher :start_with, :start_with
describe 'something' do
it 'must start with...' do
page = 'my reply'
page.must_start_with 'my reply'
page.must_start_with 'my '
end
end
There are many ways to get what you want here. The easiest way is to not mess with assertions, expectations, or matchers at all and just use an assert. So, assuming you already have the has_reply? method defined, you could just use this:
assert page.has_reply?("my reply")
But, that doesn't get you the must_have_reply syntax you are asking for. And I doubt you really have a has_reply? method. So, let's start.
Your asked "how to get a reference to the subject (i.e. the page object)". In this case the subject is the object that the must_have_reply method is defined on. So, you should use this instead of subject. But its not as straightforward as all that. Matchers add a level of indirection that we don't have with the usual Assertions (assert_equal, refute_equal) or Expectations (must_be_equal, wont_be_equal). If you want to write a Matcher you need to implement the Matcher API.
Fortunately for you you don't really have to implement the API. Since it seems you are already intending on relying on Cabybara's have_css matcher, we can simply use Capybara's HaveSelector class and let it implement the proper API. We just need to create our own Matchers module with a method that returns a HaveSelector object.
# Require Minitest Matchers to make this all work
require "minitest/matchers"
# Require Capybara's matchers so you can use them
require "capybara/rspec/matchers"
# Create your own matchers module
module YourApp
module Matchers
def have_reply text
# Return a properly configured HaveSelector instance
Capybara::RSpecMatchers::HaveSelector.new(:css, ".comment_body", :text => text)
end
# Register module using minitest-matcher syntax
def self.included base
instance_methods.each do |name|
base.register_matcher name, name
end
end
end
end
Then, in your minitest_helper.rb file, you can include your Matchers module so you can use it. (This code will include the matcher in all tests.)
class MiniTest::Rails::ActiveSupport::TestCase
# Include your module in the test case
include YourApp::Matchers
end
Minitest Matchers does all the hard lifting. You can now you can use your matcher as an assertion:
def test_using_an_assertion
visit root_path
assert_have_reply page, "my reply"
end
Or, you can use your matcher as an expectation:
it "is an expectation" do
visit root_path
page.must_have_reply "my reply"
end
And finally you can use it with a subject:
describe "with a subject" do
before { visit root_path }
subject { page }
it { must have_reply("my reply") }
must { have_reply "my reply" }
end
Important: For this to work, you must be using 'gem minitest-matchers', '>= 1.2.0' because register_matcher is not defined in earlier versions of that gem.

RSPEC bug with a class Parser (?)

I think I hit a bug in RSPEC bug, while just trying it for the first time...
In the following example, RSPEC is sensitive to the name of the class : with 'Parser' in parser.rb file the test fails, but just renaming it 'FooParser' makes it work.
require_relative './parser.rb'
describe Parser do
it 'should do the trick' do
#parser = Parser.new "test.pas"
end
end
will complain about my constructor argument, even having a plain code like this :
class Parser
def initialize arg
end
end
The RSPEC erroneous log looks like this :
1) Parser should do the trick
Failure/Error: #parser = Parser.new "test.pas"
ArgumentError:
wrong number of arguments(1 for 0)
The spec as written in your question should work (and accomplish nothing, by the way), but I'm guessing that in your real spec you tried to use should with an implicit subject, like this:
it 'should do the trick' do
#parser = Parser.new "test.pas"
should_not be_nil
end
If you use should or should_not bare like this, Rspec has to figure out what you're testing. It'll see if you are describing a class -- which you are -- and will try to instantiate it -- in your case using Parser.new with no arguments.
You may have wanted something like this:
it 'should do the trick' do
Parser.new("test.pas").should_not be_nil
end
This is a dumb test, but maybe it illustrates (what could be) the problem.

How to run arbitrary object method from string in ruby?

So I'm fairly new to ruby in general, and I'm writing some rspec test cases for an object I am creating. Lots of the test cases are fairly basic and I just want to ensure that values are being populated and returned properly. I'm wondering if there is a way for me to do this with a looping construct. Instead of having to have an assertEquals for each of the methods I want to test.
For instace:
describe item, "Testing the Item" do
it "will have a null value to start" do
item = Item.new
# Here I could do the item.name.should be_nil
# then I could do item.category.should be_nil
end
end
But I want some way to use an array to determine all of the properties to check. So I could do something like
propertyArray.each do |property|
item.#{property}.should be_nil
end
Will this or something like it work? Thanks for any help / suggestions.
object.send(:method_name) or object.send("method_name") will work.
So in your case
propertyArray.each do |property|
item.send(property).should be_nil
end
should do what you want.
If you do
propertyArray.each do |property|
item.send(property).should be_nil
end
within a single spec example and if your spec fails then it will be hard to debug which attribute is not nil or what has failed. A better way to do this is to create a separate spec example for each attribute like
describe item, "Testing the Item" do
before(:each) do
#item = Item.new
end
propertyArray.each do |property|
it "should have a null value for #{property} to start" do
#item.send(property).should be_nil
end
end
end
This will run your spec as a different spec example for each property and if it fails then you will know what has failed. This also follows the rule of one assertion per test/spec example.
A couple points about Object#send()...
You can specify parameters for the method call too...
an_object.send(:a_method, 'A param', 'Another param')
I like to use this other form __send__ because "send" is so common...
an_object.__send__(:a_method)

Resources