Easy AR association stubbing


#1

I’ve added a method to the mock class that makes it pretty easy to
stub associations in rails. I’ve been using it for awhile and it seems
to cut down on a lot of setup code for the controller and model specs
that use associations.

#before
@person = mock_model(Person)
posts = mock(‘post_proxy’)
posts.stub!(:build).and_return(mock_model(Post, :save => true))
@person.stub!(:posts).and_return(posts)

now

@person = mock_model(Person)
@person.stub_association!(:posts, :find_by_title => mock_model(Post))

Just add this to the spec helper

module Spec
module Mocks
module Methods
def stub_association!(association_name, methods_to_be_stubbed =
{})
mock_association = Spec::Mocks::Mock.new(association_name.to_s)
methods_to_be_stubbed.each do |method, return_value|
mock_association.stub!(method).and_return(return_value)
end
self.stub!(association_name).and_return(mock_association)
end
end
end
end


#2

Thanks I’ll give it a try and praise you later.


#3

But what if I need to use posts as such?

@person = mock_model(Person)
@person.stub_association!(:posts, :find_by_title => mock_model(Post))

posts.stub!(:count).and_return(2)


#4

On 10/6/07, Andrew WC Brown removed_email_address@domain.invalid wrote:

http://rubyforge.org/mailman/listinfo/rspec-users

Take a look at the source: you can pass in whatever methods you want
to be stubbed. So, for example,

@person.stub_association!(:posts, :find_by_title => mock_model(Post),
:count => 2)

Also, you should be able to stub after the fact like so:

@person.posts.stub!(:count).and_return 2

Pat


#5

you no longer have @players

try
assigns[:players].should eql(@game.players)


#6

Here’s my old association:

@game = mock_game(:to_param => "1")
Game.stub!(:find).and_return(@game)
@players = mock('player_proxy')
@players.stub!(:build).and_return(mock_model(Player, :save => true))
@game.stub!(:players).and_return(@players)

Here’s one of my specs:

it “should assign the found players for the view” do
do_get
assigns[:players].should eql(@players)

end

Everything works great. So I try to use assoication_stub!

@game = mock_game(:to_param => "1")
Game.stub!(:find).and_return(@game)
@game.stub_association!(:players, :build => mock_model(Player, :save 

=>
true))

‘PlayersController handling GET /saltmines/games/1/players should assign
the
found players for the view’ FAILED
expected nil, got #<Spec::Mocks::Mock:0x1a53358 @name=“players”> (using
.eql?)
/Volumes/EXTERNAL/web/omenking.ca/spec/controllers/players_controller_spec.rb:103:
/Volumes/EXTERNAL/web/omenking.ca/spec/controllers/players_controller_spec.rb:63:

Any suggestions?