Good day all :-)<br><br>I am getting into RSpec and am a little confused by an aspect of mocks / mock_models in controller tests. I've gone through the online docs and the PeepCode movies and have them slightly contradictory on this matter. I hope you can clarify. Many thanks in advance :-)
<br><br>I'm writing a system that uses the restful authentication plugin and am writing a test for the following controller create method:<br><br>class AccountsController < ApplicationController<br> def create<br>
@account = Account.new(params[:account])<br> if @account.save!<br> self.current_account = @account<br> redirect_back_or_default('/')<br> flash[:notice] = "Thanks for signing up!"<br>
end<br> rescue ActiveRecord::RecordInvalid<br> render :action => 'new'<br> end<br>...<br>end<br><br>I've created the following spec test to simply ensure that the Account model receives a call to :new, but the spec is failing as it also receives a call to :save! and it isn't expecting it. I am using "@account = mock_model(Account)". If i replace this with "@account = mock('account', :null_object => true)" the test passes, but i'm not sure that's really what i want. I'm pretty sure i need to us mock_model in this instance.
<br><br>The code is below. <br><br>Also, are my use of comment blocks within the spec against the RSpec *way*. I appreciate that this isn't using fixtures and i might use them later. I also appreciate that i can write modules to contain these methods, but i can't quite see the point in muddying things. Comments most welcome.
<br><br>Thanks<br><br>describe AccountsController, "allows users to create only valid accounts" do<br><br> ####### <br> ### Reusable methods<br> #######<br><br> def do_post(params = nil)<br> post :create, :account => params
<br> end<br> <br> def valid_account_form_details<br> { :password => "password", :password_confirmation => "password", :login => "new_login", :email => "<a href="mailto:test@test.com">
test@test.com</a>" }<br> end<br><br> #######<br> ### Before block<br> #######<br><br> before do<br> @account = mock_model(Account)<br> Account.stub!(:new).and_return(@account)<br> end<br><br> #######
<br> ### It Statements<br> #######<br><br> it "should display the new account template when the user visits /accounts/new" do<br> get 'new'<br> response.should render_template(:new)<br> end
<br> <br> it "should tell the Account model to create a new account on form POST" do<br> Account.should_receive(:new).with(:anything).and_return(@account)<br> do_post<br> end<br><br>