Skip to content

Instantly share code, notes, and snippets.

@daveyeu
Created January 9, 2009 12:13
Show Gist options
  • Save daveyeu/45096 to your computer and use it in GitHub Desktop.
Save daveyeu/45096 to your computer and use it in GitHub Desktop.
require File.expand_path(File.dirname(__FILE__) + "/../spec_helper")
require "activeresource"
require "active_resource/http_mock"
require "ruby-debug"
class RemotePerson < ActiveResource::Base
self.site = "http://localhost:3000"
self.element_name = "person"
end
describe PeopleController do
before do
@david = Person.create(:name => "David", :age => 28)
@david_xml = %(<?xml version="1.0" encoding="UTF-8"?><person><id type="integer">1</id><name>David</name><age type="integer">28</age></person>)
@invalid_xml = %(<?xml version="1.0" encoding="UTF-8"?><person><id type="integer">1</id><name>David</name><age type="integer">28</age></person><person />)
end
describe "#show" do
it "should respond with AR-consumable XML" do
mock_ar_response_for(:get, "/people/1.xml") do
get :show, :id => @david.to_param, :format => "xml"
end
remote_person = nil
lambda { remote_person = RemotePerson.find(@david.to_param) }.should_not raise_error
remote_person.name.should == "David"
remote_person.age.should == 28
end
it "should fail with blatantly invalid XML" do
mock_ar_response_for(:get, "/people/1.xml") do
get :show, :id => @david.to_param, :format => "xml"
response.body = @invalid_xml
end
lambda { remote_person = RemotePerson.find(@david.to_param) }.should raise_error
end
it "should fail if the mocked URL doesn't match the AR request URL" do
mock_ar_response_for(:get, "/people/1.xml") do
get :show, :id => @david.to_param, :format => "xml"
response.body = @invalid_xml
end
lambda { RemotePerson.find(2) }.should raise_error
end
end
describe "#create" do
it "should succeed" do
mock_ar_response_for(:post, "/people.xml") do
post :create, :person => { :name => "Sorry", :age => 10 }, :format => "xml"
end
lambda { RemotePerson.create(:name => "Sorry", :age => 10) }.should_not raise_error
end
it "should fail if the Location header isn't set" do
mock_ar_response_for(:post, "/people.xml") do
post :create, :person => { :name => "Sorry", :age => 10 }, :format => "xml"
response.headers.delete("Location")
end
lambda { RemotePerson.create(:name => "Sorry", :age => 10) }.should raise_error
end
end
end
def mock_ar_response_for(method, url, &block)
yield
ActiveResource::HttpMock.respond_to do |mock|
mock.send(method, url, {}, response.body, response.code, response.headers)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment