Hi everybody,
my name is Olaf, I’m living in Berlin and this is my first post. I’m
quite new to rpsec, so please forgive my Newbieness! I’ve a problem
stubbing a simple update action in a controller. I use a little hack
to stub AR associations. So I added to my rspec_helper.rb the
following code:
Stubbing Associations
module Spec
module Mocks
module Methods
def stub_association!(association_name, methods_to_be_stubbed =
{})
mock_association =
Spec::Mocks::Mock.new(association_name.to_s)
methods_to_be_stubbed.each do |method, return_value|
mock_association.stub!(method).and_return(return_value)
end
self.stub!(association_name).and_return(mock_association)
end
end
end
end
No I want to test the following action in my controller:
def update
@profilecategory = @user.profilecategories.find(params[:id])
respond_to do |format|
if @profilecategory.update_attributes(params[:profilecategory])
flash[:notice] = _(‘Category was successfully updated.’)
format.html { render :action => “index” }
format.js
else
format.html { render :action => “edit” }
format.js
end
end
end
This is my Rspce code for doing so:
describe ProfilecategoriesController do
before(:each) do
@current_user = mock_model(User)
@profilecategory = mock_model(Profilecategory)
@current_user.stub_association!(:profilecategories, :build =>
@profilecategory,
:find => @profilecategory)
@user = @current_user
controller.stub!(:current_user).and_return(@current_user)
end
describe “handling PUT /profilecategories/3 with successfull save” do
it_should_behave_like “the user is logged in”
before(:each) do
@profilecategory.stub!(:update_attributes).and_return(true)
end
def do_put
put :update, :id => '3', :profilecategory => {:name => 'new
name’}
end
it "should be successfull" do
do_put
response.should be_success
end
it "should find the object" do
@user.profilecategories.should_receive(:find).with(‘3’).and_return(@profilecategory)
do_put
end
it "should call the update_attributes function" do
@profilecategory.should_receive(:uptdate_attributes).with({:name
=> ‘new name’}).and_return(true)
do_put
end
end
end
When I run the rspec file, I always get this error:
should call the update_attributes function
Mock ‘Profilecategory_1034’ expected :uptdate_attributes with
({:name=>“new name”}) once, but received it 0 times
I don’t understand this. My Associations seem to work and when calling
the update action in the browser, everything works fine. I guess it
has something to do with AR not caching the associations. But I don’t
know how to solve this problem.
I also thought about this approach, but didn’t get it to work
properly:
@profilecategories = mock(Profilecategory)
@user.stub!(:profilecategories).and_return(@profilecategories)
It would be great, if anyone could help me with that! I don’t know,
what to do!
Best regards,
Olaf