Has anyone seen this strange mock behaviour?

I’ve got this example ‘group’:

before(:all) do
@mock_user = mock_model(User)
@mock_email_field = mock_model(EmailField, :user => @mock_user)
@mock_email_field.stub!(:user).and_return(@mock_user)
EmailField.stub!(:find_by_value).and_return(@mock_email_field)
end

it “should find existing user by email when asked for
group_user_from_attributes” do
# @mock_email_field.stub!(:user).and_return(@mock_user)
EmailField.should_receive(:find_by_value).with(“[email protected]”).and_return(@mock_email_field)
User.group_user_from_attributes(:email=>“[email protected]”)
end

This fails with a message:
should find existing user by email when asked for
group_user_from_attributes
Mock ‘EmailField_1001’ received unexpected message :user with (no args)

Note that I defined the @mock_email_field to stub the user method.

If I uncomment the restubbing of the @mock_email_field in the example,
it works.

It certainly seems that @mock_email_field points to the same object in
either case.

I’ve also tried using stub! in the before block instead or or in
addition to hash stub in mock_model, but unless I stub it in the
example no joy.

A couple of us have been scratching our heads over this and I thought
I’d throw it out to the wider RSpec community.


Rick DeNatale

My blog on Ruby
http://talklikeaduck.denhaven2.com/

On Mon, Mar 24, 2008 at 4:38 PM, Rick DeNatale [email protected]
wrote:

I’ve got this example ‘group’:

before(:all) do
@mock_user = mock_model(User)
@mock_email_field = mock_model(EmailField, :user => @mock_user)
@mock_email_field.stub!(:user).and_return(@mock_user)
EmailField.stub!(:find_by_value).and_return(@mock_email_field)
end

before(:all) will only be executed once - before all of your examples.
Why are you using before(:all)?

It’s highly recommended you don’t use before(:all) - and definitely
not with mocks. All sort of sideeffects might happen.

Aslak

On Mon, Mar 24, 2008 at 11:54 AM, aslak hellesoy
[email protected] wrote:

before(:all) will only be executed once - before all of your examples.
Why are you using before(:all)?

Because I had a brain f*rt.

Actually I just caught this myself before checking back with the list.

Thanks!


Rick DeNatale

My blog on Ruby
http://talklikeaduck.denhaven2.com/

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs