Trouble Testing a Controller With RSpec

Hello-

I've been staring that this problem for hours with no success. What
I'm trying to do is pretty simple. I'm trying to test the create
method of a controller.

Here is the create method:

  # POST /accounts
  def create
    @account = Account.new(params[:account])

    respond_to do |format|
      if @account.save
        flash[:notice] = 'Account was successfully created.'
        format.html { redirect_to account_url }
      else
        format.html { render :action => "new" }
      end
    end
  end

My Account class only has two fields: name and subdomain.

Here is the code for my test:

    before(:each) do
      @account = mock_model(Account, :to_param => "1")
      Account.stub!(:new).and_return(@account)
    end

    def do_post
      @account.should_receive(:save).and_return(true)
      post :create, :account => { :subdomain => 'test' }
    end

My test is failing because of the line in my controller "format.html
{ redirect_to account_url }". I'm using the account location plugin
and when the account_url method is called, it is looking for
@account.subdomain, which is not set. In fact, any parameters I pass
in to the call to "post" in my test seem to be ignored.

Am I doing something wrong? Thanks in advance.

-Eric

before(:each) do

  @account = mock_model(Account, :to_param => "1")

  Account.stub!(:new).and_return(@account)

controller.stub!(account_url).and_return(“redirect_value”)

end

def do_post

  @account.should_receive(:save).and_return(true)

  post :create, :account => { :subdomain => 'test' }

end

My test is failing because of the line in my controller "format.html

{ redirect_to account_url }". I’m using the account location plugin

and when the account_url method is called, it is looking for

@account.subdomain, which is not set.

So stub it out, see above.

Hi Rick. Thanks for the reply. Is stubbing that out a hack or the best
way to appraoch this. I'm worried that by stubbing out the account_url
method, I won't be testing whether or not the account_url method is
properly accessing @account or that @acount is being preoperly set
from the params. Granted, a case could be made that those are separate
tests or are unnecessary (given that testing params is more testing
Rails than my code). What are our thoughts? Thanks again.

-Eric

I’d consider the account_url helper to be part of rails, and in any case outside of the scope of this controller’s spec.

In your original post you mentioned a plugin which seems to be affecting account_url, in which case I’d expect this to be specified in the tests/specs for that plugin.