Skip to content

Instantly share code, notes, and snippets.

@cupakromer
Created July 18, 2014 21:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cupakromer/80de9c85107725979382 to your computer and use it in GitHub Desktop.
Save cupakromer/80de9c85107725979382 to your computer and use it in GitHub Desktop.
Trying out some new RSpec `shared_example` ideas
require 'domain/exportable_widget'
require 'support/preconditions'
RSpec.describe ExportableWidget do
# We don't know yet if we will have multiple exportable objects, but this
# is simply the documentation of our intended shared protocol if we do later.
shared_examples_for "an exportable" do
required_attribute :exportable
it "has an authorization token" do
expect(exportable.auth_token).to be_a String
end
it "has a last exported at timestamp" do
expect(exportable.last_exported_at).to be_a DateTime
end
it "can have a nil last exported timestamp if it was never exported" do
expect{
expect{
exportable.last_exported_at = nil
}.to change(exportable, :last_exported_at).to(nil)
}.to change(exportable, :exported?).from(true).to(false)
# The following matcher will be available / fixed in 3.1.0 possibly 3.0.3
#}.to change(exportable, :exported?).to(true)
# .and change(exportable, :last_exported_at).to(nil)
end
end
subject(:any_exportable_widget) {
ExportableWidget.new(
widget_id: a_sample_widget_id,
auth_token: SecureRandom.uuid,
last_exported_at: 1.day.ago,
)
}
let(:a_sample_widget_id) { 1 }
it_behaves_like "an exportable" do
subject(:exportable) { any_exportable_widget }
end
it "has a widget id" do
expect(any_exportable_widget.widget_id).to eq a_sample_widget_id
end
end
RequiredAttributeError = Class.new(RuntimeError)
module MyApp
module RSpec
module Preconditions
def required_attribute(bareword)
# TODO: Figure out how to get the calling line in the error and not
# the `fail` line below
before do
bareword = bareword.intern
unless respond_to?(bareword) && !send(bareword).nil?
fail RequiredAttributeError, "No `#{bareword}` object provided"
end
end
end
end
end
end
RSpec.configure do |config|
config.extend MyApp::RSpec::Preconditions
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment