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])

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
  # now what do I stub, if anything?

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.

Need Your Help

Using gulp to combine and edit multiple json files into one

json gulp

I'm a little bit into gulp and I'm looking for the right combination of tasks to read n amount of similarly formatted json files, pull out a specific array from each, combine them, and save as a new

Custom Soft keyboard Layouts

android android-layout android-input-method soft-keyboard

Im creating a softkeyboard Input Method service and I was wondering if it is possible to add several layout layers for instance placing the keyboard within a FrameLayout and then showing it within ...