Skip to content

Instantly share code, notes, and snippets.

@kern
Created October 17, 2012 10:05
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 kern/3904791 to your computer and use it in GitHub Desktop.
Save kern/3904791 to your computer and use it in GitHub Desktop.
How would you test Person in isolation?
require "virtus"
require "rspec/autorun"
class Address < Virtus::Attribute::Object
primitive String
def coerce(value)
# Simulate a slow call to an external service that normalizes the
# address's format.
sleep 1
"123 Foobar Street, Berkeley, CA 94720"
end
end
class Person
include Virtus
attribute :name, String
attribute :address, Address
end
describe Person do
subject(:person) { described_class.new(:name => "Bob", :address => "Nowhereland") }
before do
# Somehow stub out the coercion method for the address here so that the
# test runs quickly in isolation.
end
it "has a name" do
expect(person.name).to eq("Bob")
end
it "has an address" do
expect(person.address).to eq("123 Foobar Street, Berkeley, CA 94720")
end
end
@solnic
Copy link

solnic commented Oct 17, 2012

@CapnKernul you could try this:

class Address < Virtus::Attribute::String
  def coerce(value)
    # slow stuff happens here
  end
end

before do
  Person.attribute_set[:address].stub!(:coerce).and_return("Nowhereland")
end

Alternatively you could also do this:

class NormalizedAddress
  def initialize(address)
   @address = address
  end

  def normalize
    # some slow stuff happens here
  end
  alias_method :to_str, :normalize
end

class Person
  include Virtus

  attribute :name, String
  attribute :address, String
end

Person.new(:name => 'John', :address => NormalizedAddress.new('some funky address')

@kern
Copy link
Author

kern commented Oct 17, 2012

@solnic Perfect! Thank you. :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment