[rspec-users] Mocking and stubbing Rails' association extensions

David Chelimsky dchelimsky at gmail.com
Thu Jan 10 13:40:40 EST 2008


On Jan 10, 2008 12:35 PM, Chris Kampmeier <chris at kampers.net> wrote:
> I'm having a lot of trouble stubbing out an association extension for
> some view tests. Example rails code modeling a music album:
>
> class Album < ActiveRecord::Base
>    has_many :songs do
>      def streamable
>        find(:all, :conditions => 'streamable = 1')
>      end
>    end
> end
>
> So for a given Album instance (say @album), I need to be able to stub
> both @album.songs and @album.songs.streamable in the same before block.
>
> Is there a way for a stub to return one thing when called alone
> (@album.songs) and another stub when the call is chained?
> (@album.songs.streamable)
>
> Before adding the extension, I just had @album.songs returning an
> array of Song instances. The only thing I've thought of that would
> work is temporarily extending Array itself to respond to #streamable,
> but that feels ugly.

album = mock("album")
songs = mock("songs")
album.stub!(:songs).and_return(songs)
songs.stub!(:streamable).and_return(true)

That's the general idea. Specifics will vary for each example.

Cool?

>
> Thanks for any ideas,
>
> Chris Kampmeier
> http://www.shiftcommathree.com
>
>
>
> _______________________________________________
> rspec-users mailing list
> rspec-users at rubyforge.org
> http://rubyforge.org/mailman/listinfo/rspec-users
>


More information about the rspec-users mailing list