Skip to content

Instantly share code, notes, and snippets.

@pseudomuto
Last active December 21, 2015 16:09
Show Gist options
  • Save pseudomuto/6331289 to your computer and use it in GitHub Desktop.
Save pseudomuto/6331289 to your computer and use it in GitHub Desktop.
Blog Code: Drying Out Specs with Shared Examples
require "spec_helper"
describe SimpleClass do
before do
subject.name = "Some Name"
subject.description = "Some Description"
end
its(:name) { should eq("Some Name") }
its(:description) { should eq("Some Description") }
end
class SimpleClass
attr_accessor :name, :description
end
require "spec_helper"
describe SimpleClass do
before do
subject.name = "Some Name"
subject.description = "Some Description"
end
its(:name) { should eq("Some Name") }
its(:description) { should eq("Some Description") }
describe "#name" do
context "when not supplied" do
before do
subject.name = ""
subject.valid?
end
it { should_not be_valid }
it "should have an error" do
expect(subject.errors.size).to eq(1)
expect(subject.errors[:name]).to_not be_nil
end
end
end
describe "#description" do
context "when not supplied" do
before do
subject.description = ""
subject.valid?
end
it { should_not be_valid }
it "should have an error" do
expect(subject.errors.size).to eq(1)
expect(subject.errors[:description]).to_not be_nil
end
end
end
end
# you can omit the version if you don't need it
gem "activemodel", "~> 4.0.0"
require "active_model"
class SimpleClass
include ::ActiveModel::Validations
attr_accessor :name, :description
validates_presence_of :name, :description
end
require "spec_helper"
describe SimpleClass do
before do
subject.name = "Some Name"
subject.description = "Some Description"
end
its(:name) { should eq("Some Name") }
its(:description) { should eq("Some Description") }
shared_examples_for "a required property" do
# requires that "field" be defined
before do
subject.__send__("#{field}=", "")
subject.valid?
end
it { should_not be_valid }
it "should have an error" do
expect(subject.errors.size).to eq(1)
expect(subject.errors[field]).to_not be_nil
end
end
describe "#name" do
context "when not supplied" do
let(:field) { :name }
it_should_behave_like "a required property"
end
end
describe "#description" do
context "when not supplied" do
let(:field) { :description }
it_should_behave_like "a required property"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment