[rspec-users] describe AddressesController, "handling GET /addresses" do

Pat Maddox pergesu at gmail.com
Thu Nov 22 11:48:37 EST 2007


On Nov 22, 2007 3:24 AM, Sahyoun <osahyoun at gmail.com> wrote:
> Pat, thanks. That helped. I'm now trying to get my head around the error:
>
> Spec::Mocks::MockExpectationError in 'AddressesController handling GET
> /addresses/1 should be successful'
> Mock 'Address_1006' received unexpected message :find with ("1")
>
> My show method in the addresses controller:
>   def show
>     @address = @company.addresses.find(params[:id])
>
>     respond_to do |format|
>       format.html # show.html.erb
>
>       format.xml  { render :xml => @address }
>     end
>   end
>
> In the controller spec:
>
> describe AddressesController, "handling GET /addresses/1" do
>
>   before do
>     @address = mock_model(Address)
>     @company = mock_model(Company)
>
>     Company.stub!(:find_by_id).and_return(@company)
>     @company.stub!(:addresses).and_return(@address)
>   end
>
>   def do_get
>     get :show, :id => "1", :company_id => "1"
>
>   end
>
>   it "should be successful" do
>     do_get
>     response.should be_success
>   end
>
> ....
>
>
> I know that @company.stub!(:addresses).and_return(@address) is incorrect.
> I'm trying to work out how I can stub out:
> @address = @company.addresses.find(params[:id])
>
> Thanks for any pointers.
>
> Omar

The problem is that you didn't stub #find on the addresses proxy.
Here's how I'd write it:

describe AddressesController, "handling GET /addresses/1" do

  before do
    @address_proxy = mock("address proxy", :find => :address)
    @company = mock_model(Company)

    Company.stub!(:find_by_id).and_return(@company)
    @company.stub!(:addresses).and_return(@address_proxy)
  end

  def do_get
    get :show, :id => "2", :company_id => "1"
  end


  it "should be successful" do
    do_get
    response.should be_success
  end

  it "should find the company" do
    Company.should_receive(:find_by_id).with("1").and_return @company
    do_get
  end

  it "should find the address" do
    @address_proxy.should_receive(:find).with("2").and_return :address
    do_get
  end

  it "should assign the address to the view" do
    do_get
    assigns[:address].should == :address
  end

  it "should render show.rhtml" do
    do_get
    response.should render_template(:show)
  end
end

hth
Pat


More information about the rspec-users mailing list