views:

513

answers:

2

Hi, I'm writing a spec for my Rails controller, this is the action I'm testing:

def create
  @course = Course.new(params[:course])
  if @course.save then
    #flash[:notice] = 'Course Created'
    redirect_to courses_path
  else
    render :action => 'new', :status => 400
  end
end

And this is the spec that validates it:

describe "POST /courses [Good Input]" do

  it "should redirect to Courses index page after creation" do
    @course.stub!(:save).and_return(true)
    post :create
    response.should be_success
    response.should redirect_to(courses_path)
  end

end

Still I'm getting this error from RSpec:

'CoursesController POST /courses [Good Input]

should redirect to Courses index page after creation'

FAILED

expected redirect to "/courses", got no redirect

Any ideas why this happens?

SOLVED

as rishavrastogi stated, *should be_success* expects a http code on the 2xx range, and a redirect falls into the 3xx range (actually its 302)

The assertion needs to be changed to => *response.should be_redirect*.

Although in this case, it's redundant to check that the response is a redirect and then checking that redirects to an specific page, so that assertion is not needed anymore.

A: 

I'm not a rspecer, but afaik you have to do something like assigns(:course).stub!.... Instance variables in specs aren't the same as instance variables in controllers, assigns so lets you access the controller ones.

August Lilleaas
Sorry I should have stated that in the before block I do Course.stub!(:new).and_return(@course) which is a dummy object I create...
Pablo Fernandez
+2  A: 

I mnt a rspecer either but

I guess "response.should be_success" shouldn't be there because the response is actually a

"HTTP redirect" not "HTTP success" ... so try removing response.should be_success

Also

change

 post :create 

to

 post :create, :course => {} 
Rishav Rastogi
why should I change post :create?
Pablo Fernandez
actually that may not be required until you want to pass some values of instance variables for example "post :create ,:course => {:title=> "something" }.. " etc..this may be required when working with validations
Rishav Rastogi
Ok. Thanks. I'm mocking everything (like Course.new and Course.find)... so I really don't need that, but it's a good point anyway
Pablo Fernandez