Skip to content

Instantly share code, notes, and snippets.

@ashmoran
Forked from mattwynne/sketch.rb
Created June 29, 2012 16:04
Show Gist options
  • Save ashmoran/3018833 to your computer and use it in GitHub Desktop.
Save ashmoran/3018833 to your computer and use it in GitHub Desktop.
sketch for Matt Wynne
class Organization
def to_param
"42"
end
def saved?
rand > 0.5
end
end
class OrganizationCreator
def create_for(user, org_name, callbacks)
# real creation logic here
organization = Organization.new
if organization.saved?
callbacks[:success].call(organization)
else
callbacks[:failure].call(organization)
end
end
end
class OrganizationsController
def create
params = { organization: 'Hello' }
creator = OrganizationCreator.new
creator.create_for(current_user, params[:organization],
success: ->(org) { redirect_to organizations_path(org) },
failure: ->(org) { render :error }
)
end
private
def redirect_to(path)
puts "redirecting_to #{path}"
end
def render(renderable)
puts "rendering #{renderable}"
end
def current_user
Object.new
end
def organizations_path(org)
"/organizations/#{org.to_param}"
end
end
# controller = OrganizationsController.new
# controller.create
describe OrganizationCreator do
let(:creator) { OrganizationCreator.new }
let(:organisation) { stub(Organization, saved?: saved_result) }
before(:each) do
Organization.stub(new: organisation)
end
context "success" do
let(:saved_result) { true }
it "calls the success callback" do
callback_called = nil
creator.create_for(nil, nil,
success: ->(org) { callback_called = :success_called }
)
callback_called.should be == :success_called
end
end
context "failure" do
let(:saved_result) { false }
it "calls the success callback" do
callback_called = nil
creator.create_for(nil, nil,
failure: ->(org) { callback_called = :failure_called }
)
callback_called.should be == :failure_called
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment