On 2008-11-25, at 22:07, David Parker wrote:
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

Hi David. To write specs for ActiveRecord associations, I find Matthew Heidemann's #stub_association! extremely helpful. There was a discussion about it last week, actually:
  http://www.ruby-forum.com/topic/171076

I hope that helps. Cheers,
Nick
_______________________________________________
rspec-users mailing list
rspec-users@rubyforge.org
http://rubyforge.org/mailman/listinfo/rspec-users

Reply via email to