[rspec-users] rails associations

David Parker davidwparker at gmail.com
Tue Nov 25 22:07:25 EST 2008


Hello!

So I'm having some problems working out some probably really easy
associations in Rails.  I've Googled around and read some things on
different Rails forums and blogs, but I just haven't seen many solid
examples.

Anyway, my question is a basic "how do I use RSpec with stubs/mocks through
associations for methods"...
perhaps code would be more clear.  Here's my controller:

  def create
    @article = current_account.article.create(params[:article])
    respond_to do |format|
      if @article.save
        flash[:success] = 'Article was successfully saved.'
        format.html { redirect_to(accounts_article_path(@article)) }
      else
        format.html { render :action => "new" }
      end
    end
  end

And here is my corresponding spec:

  describe "handling POST /accounts/articles" do
    before(:each) do
      @article = mock_model(Article, :to_param => '1')
      @account   = mock_model(Account)
      controller.stub!(:current_account).and_return(@account)
      @account.stub!(:articles).and_return(@article)
      @article.should_receive(:create)
    end

    describe "with successful save" do
      def do_post
        @article.should_receive(:save).and_return(true)
        post :create, :article => {}
      end

      it "should redirect to the new article" do
        do_post
        response.should redirect_to(accounts_article_url(@article))
      end
    end

    describe "with failed save" do
      def do_post
        @article.should_receive(:save).and_return(false)
        post :create, :article => {}
      end

      it "should re-render 'new'" do
        do_post
        response.should render_template('new')
      end
    end
  end

I'm getting a couple of errors from this and I can't tell why.  I have
something similar done for non-associated models with no problem.
NoMethodError in 'Accounts::ArticlesController handling POST
/accounts/articles with failed save should re-render 'new''
You have a nil object when you didn't expect it!

I'm sure that speccing associations can't be that bad... I just don't really
know what to look for.

Dave, I can't wait for your book to come out!

Thanks for the help!

David Parker
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://rubyforge.org/pipermail/rspec-users/attachments/20081125/774f7960/attachment-0001.html>


More information about the rspec-users mailing list