How to mock an association

I’ve got a “group” model that has a user_id attribute and a
validates_existence_of :user and validates_presence_of :user_id
validations. What method(s) do I need to stub on the User mock to
intercept those validation calls? My goal is to isolate the Group model
from the User model.

Thanks

Wes

On Feb 11, 2008 1:43 PM, Wes S. [email protected] wrote:

I’ve got a “group” model that has a user_id attribute and a
validates_existence_of :user and validates_presence_of :user_id
validations. What method(s) do I need to stub on the User mock to
intercept those validation calls? My goal is to isolate the Group model
from the User model.

See Mocking and stubbing Rails' association extensions - RSpec - Ruby-Forum

and http://tersesystems.com/post/9700067.jhtml

Obvious ‘rails mocking associations’ seemed to work for me, unless I
misunderstood the question.

Of course, you could just stub ‘valid?’ for any AR object as well.

“One day, when he was naughty, Mr Bunnsy looked over the hedge into
Farmer Fred’s field and it was full of fresh green lettuces. Mr
Bunnsy, however, was not full of lettuces. This did not seem fair.”
– Terry Pratchett, Mr. Bunnsy Has An Adventure

Obvious ‘rails mocking associations’ seemed to work for me, unless I

…make that ‘…Googling for …’. Duh.


“One day, when he was naughty, Mr Bunnsy looked over the hedge into
Farmer Fred’s field and it was full of fresh green lettuces. Mr
Bunnsy, however, was not full of lettuces. This did not seem fair.”
– Terry Pratchett, Mr. Bunnsy Has An Adventure

I don’t know exactly how you’re using the code, but
validates_presence_of
:user_id seems redundant. If you’ve setup a relationship from Group to
User
then Active Record will be enforcing that validation for you. Just a
thought

Other than that you would probably do (without seeing any of your code):

group = mock_model(Group, :to_param => 1)
user = mock_model(User, :to_param => 1)

group.stub!(:user).and_return(user)

On Mon, Feb 11, 2008 at 8:21 AM, Edvard M. [email protected]
wrote:

rspec-users mailing list
[email protected]
http://rubyforge.org/mailman/listinfo/rspec-users


Bryan R.

“Programming today is a race between software engineers striving to
build
bigger and better idiot-proof programs, and the Universe trying to
produce
bigger and better idiots. So far, the Universe is winning.”