On Jun 28, 2008, at 7:27 PM, Britt Mileshosky wrote:
an example that sets an expecation at the top or beginning of an
this filter so that I don’t receive ‘unexpected method’ errors, or
do_get
action to prevent it from doing anything, you could of course just
which is why it works nicely.
here?
end
controller
.should_receive(:current_user).and_return(@mockUser).end_example
Am i going about it all wrong? Is there something I’m missing or
does this just seem natural…
You’re doing the right thing by handling the stubs before(:each) -
that’s what it’s therefore - to set up the environment so things will
run.
I would recommend avoiding instance variable assignment there,
however. If you need a variable, create it directly in the example.
This is something that I’ve only recently started doing and I find
that it keeps things much more clear.
There are a few things you can do to tidy up the stubs a bit. You
could organize things differently to express the relationships better:
before(:each) do
controller.stub!(:current_user).and_return(stub_model(User))
controller.stub!(:has_account?).and_return(true)
controller.stub!(:current_account).and_return(
stub_model(UserAccount,
:people => stub(‘people’,
:find => stub_model(Person)
)
)
)
end
If you wrap self.people.find in self.find_person in Account (which
fixes the Law of Demeter violation), like this:
def some_action
@user = self.current_user
@account = self.current_account if self.has_account?
@person = @account.find_person(params[:person])
end
… you can reduce the before to this:
before(:each) do
controller.stub!(:current_user).and_return(stub_model(User))
controller.stub!(:has_account?).and_return(true)
controller.stub!(:current_account).and_return(
stub_model(UserAccount,
:find_person => stub_model(Person)
)
)
end
In cases like current_user, you don’t really need to stub that because
the controller will just return nil.
If has_account? actually checks for current_account.nil?, then you
don’t have to stub that either. Now you just have this:
before(:each) do
controller.stub!(:current_account).and_return(
stub_model(UserAccount,
:find_person => stub_model(Person)
)
)
end
This is a bit more organized, but still quite busy. In the end, when
you’re dealing with code that violates Tell, Don’t Ask (which is quite
natural in Rails controllers), you have to stub a lot of stuff to get
the isolation you want. It’s a tradeoff.
HTH,
David