[rspec-users] How to write a correct RSpec for Polymorphic Association

Sergey Rogachev lists at ruby-forum.com
Fri Oct 16 08:21:10 EDT 2009


I don't know what is need to set in the variable ADDRESSES:
Organization.stub!(:find_by_id).with("100").and_return(mock_organization(:id
=> "100", :addresses => ??? ))

Somebody help me. Any ideas? I tried to find the solution of problem but
I can't.

--- rspec - controllers
def mock_organization(stubs={})
  @parent_object ||= mock_model(Organization, stubs)
end

it "assigns a newly created address as @address" do
  Organization.stub!(:find_by_id).with("100").and_return(
       mock_organization(:id => "100", :addresses => ??? )) <<!--- here
  @parent_object.stub(:addresses).stub(:new).with({:these => 'params'})

  post :create, :address => {:these => 'params'}, :organization_id =>
@parent_object.id
  assigns[:address].should equal(mock_address)
end

---- models ----
class Organization < ActiveRecord::Base
  has_many :addresses, :as => :addressable
end

class Address < ActiveRecord::Base
  belongs_to :addressable, :polymorphic => true
end

----- controllers -----
class AddressesController < ApplicationController
  before_filter :load_parent_object

  def create
    @address = @parent_object.addresses.new(params[:address])

    respond_to do |format|
      if @address.save
        flash[:notice] = 'Address was successfully created.'
        format.html { redirect_to(@parent_object) }
        format.xml  { render :xml => @address, :status => :created,
:location => @address }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @address.errors, :status =>
:unprocessable_entity }
      end
    end
  end

  private

  def load_parent_object
    if params[:organization_id]
      @parent_object = Organization.find_by_id(params[:organization_id])
    end
  end

end
-- 
Posted via http://www.ruby-forum.com/.


More information about the rspec-users mailing list