Easy AR association stubbing

On 10/5/07, Andrew WC Brown <omen.king at gmail.com> wrote:

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.

Hi Matthew,

Thanks for this tip. I tried refactoring my subdomain as account keys
spec (http://rubyforge.org/pipermail/rspec-users/2007-October/
004157.html) with stub_association!, but am having some trouble.

Here’s my setup method:

before do
@request.host = “subdomain.test.host”
@item = mock_model(Item)
Item.stub!(:find).and_return(@item)
@current_company = mock_model(Company)
@current_company.stub_association!(:items, :find => [@item])
end

it “should find the item requested” do
@current_company.should_receive(:find).with(“1”).and_return(@item)
do_get
end

… fails with:
Mock ‘Company_1005’ expected :find with (“1”) once, but received it 0
times

I’m using subdomains as account keys, as in my code example here:
http://rubyforge.org/pipermail/rspec-users/2007-October/004157.html

Thanks!

  • Ryan H.

try: it “should find the item requested” do
@current_company.items.should_receive(:find).with(“1”).and_return(@item)
do_get
end

-Matt