How to properly stub a Rails association methods via mocha and test/unit?
I'm working on an app where most, if not all, of the data is scoped to a current_organization. So in my find calls in my controllers, I have things like this for example:
def show @user = current_organization.users.find(params[:id]) end
However, in my controller tests, I'm having a hard time figuring out the proper way (or any way) to stub these calls so that I can test things like:
get :show, :id => 1 assert_response :success
Those are failing saying "AR can't find user with ID=1 and organization_id = 3" or whatever. No matter what I try, I can't seem to get around it.
My setup block looks something like this:
setup do company = organizations(:company) # fixture @controller.stubs(:current_organization).returns(company) # now what do I stub, if anything? end
I tried doing stuff like: company.stubs(:users).returns([users(:one), users(:two)]) but that doesn't work because the AR find() call doesn't exist for a basic array.
Should I set the fake users array to be a variable like fake_users and then do something like fake_users.stubs(:find).returns(@user)? That didn't feel right, but maybe that's the proper way.
I'm just looking for the best way to handle this. I'm using mocha and test/unit, if that matters or helps.
Unless you specifically need access to the fake_users, I think the simplest thing you could do is probably something like this :-
company.stubs(:users => stub('users', :find => users(:one)))
Unfortunately, this kind of code is awkward to mock. You will notice that my suggested solution is rather brittle.