Forum: RSpec mocking does not work

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Leon D. (Guest)
on 2008-10-30 08:53
(Received via mailing list)
The spec
--------------------------------------------------------------------------------------------------------------------------------------------------------
it "should expose a newly created logo as @logo" do
  Logo.should_receive(:new).with({'these' =>
'params'}).and_return(mock_logo(:save => true))
  Logo.should_receive(:company=).with(mock_model(Company))
  post :create, :logo => {:these => 'params'}
  assigns(:logo).should equal(mock_logo)
end


The code:
--------------------------------------------------------------------------------------------------------------------------------------------------------
def create
  @logo = Logo.new(params[:logo])
  @logo.company = current_user.company
  puts current_user.full_name
  if @logo.save
    flash[:notice] = 'You logo was successfully uploaded.'
    redirect_to logo_setting_path
  else
    render :action => logo_setting_path
  end
end

And the error:
--------------------------------------------------------------------------------------------------------------------------------------------------------
Spec::Mocks::MockExpectationError in 'LogosController responding to POST
create
with valid params should expose a newly created logo as @logo'
Mock 'Logo_1001' received unexpected message :company= with
(#<Company:0x219a800
 @name="Company_1">)



Question:
How could I mock a company= methond on Logo?
Hans de Graaff (Guest)
on 2008-10-30 09:09
(Received via mailing list)
On Thu, 2008-10-30 at 14:47 +0800, Leon Du wrote:
> The spec
> 
--------------------------------------------------------------------------------------------------------------------------------------------------------
> it "should expose a newly created logo as @logo" do
>   Logo.should_receive(:new).with({'these' =>
> 'params'}).and_return(mock_logo(:save => true))
>   Logo.should_receive(:company=).with(mock_model(Company))
>   post :create, :logo => {:these => 'params'}
>   assigns(:logo).should equal(mock_logo)
> end

The instance of Logo should receive the company= method, not the class,
so:

@logo = mock_logo
Logo.should_receive(:new).and_return(@logo)
@logo.should_receive(:company=)

I would probably use stub! instead here and move this code into a before
block, and just keep the post and assigns lines in the it block.

Hans
Leon D. (Guest)
on 2008-10-30 11:33
(Received via mailing list)
Thanks for your reply, I did move the code to before

before(:each) do
  Logo.stub!(:new).and_return(mock_logo(:save => true, :company= =>
nil))
end

2008/10/30 Hans de Graaff <removed_email_address@domain.invalid>
This topic is locked and can not be replied to.