RSpec: stub relationship detection (chaining)

Controller:

@organization.topics.find(params[:id])

How can I drown this in my spec controller using rspec? ( @organizationIS is installed in my spec helper)

I tried:

controller.stub_chain(:topics, :find).with("37") { mock_topic }
Topic.stub(:find).with("37") { mock_topic }

None of the above work. Any ideas? Thank!

+3
source share
2 answers

If you have access to a variable @organization(you indicate that you are doing this), you should be able to:

@organization.stub_chain(:topics, :find).and_return(mock_topic)

I don't believe (unless they changed the API to stub_chain, but I don't see anything like this in the docs), you can specify .with ('37 ') when using stub_chain. If you absolutely must indicate which variable is passed to the find method (and this rarely happens), you will have to go a long route:

# This line is attempting to fake-out the .topics association and
# just return a mock of *whatever*, since it just an intermediary
# step to where we really want to get to.
topics = @organizations.stub!(:topics).and_return(mock_model(Topic))
topics.stub!(:find).with('37').and_return(mock_topic)
+3
source

You cannot just:

@organizations.topics.stub!(:find).and_return(mock_whatever)
+1
source

All Articles