-
-
Save bmabey/175849 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# code | |
class ExternalDataApi | |
def initialize(setup) | |
# do stuff to setup | |
end | |
def list_of_things | |
# grabs stuff from the api and returns an array of OStructs | |
end | |
end | |
class Thing << ActiveRecord::Base | |
def self.load_stuff_from_api | |
api = ExternalDataApi.new(setup) | |
api.list_of_things.each do |thing| | |
Stuff.create( | |
:name => thing.name, | |
:etc => thing.etc | |
) | |
end | |
end | |
end | |
# spec | |
describe Thing, ".load_stuff_from_api" do | |
before(:each) do | |
@mock_api = mock('ExternalDataApi', :list_of_things => []) | |
ExternalDataApi.stub!(:new).and_return @mock_api | |
end | |
it "initializes an ExternalDataApi with blah blah" do | |
# expect | |
ExternalDataApi.should_receive(:new).with('expected setup') # the stub from above will return @mock_api | |
# when | |
Thing.load_stuff_from_api | |
end | |
it "populates things from the api" do | |
fake_list = [OpenStruct.new(:name => "name", :etc => "etc")] | |
@mock_api.stub!(:list_of_things).and_return(fake_list) | |
Thing.count.should == 0 # this is really a sanity check and is optional since you should have a clean state at this point | |
Thing.load_stuff_from_api | |
Thing.all.map { |things| things.attributes.slice(:name, :etc) }.should == fake_list.map { |s| { :name => s.name, :etc => s.etc } } | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment