Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

post to a different controller in an rspec test

How do I post to a different controller than the one the test script is currently pointing at?

Example: in user_controller_spec.rb

  it "should just post to users" do        
    post :create, @params    # this goes to the users controller
  end

I want to do something like:

  it "should post to user and people to do some integration testing" do        
    post :create, @params    # this goes to the users controller still
    post 'people', :create, @params   # this goes to the people controller
  end

ps: i don't want to setup cucumber

like image 685
djburdick Avatar asked Sep 02 '11 23:09

djburdick


3 Answers

Controller specs are wrappers for Rails functional tests, which don't support multiple requests or controllers. What you want is an RSpec request spec (rails 3) or an integration spec (rails 2). These wrap Rails integration tests, which does support multiple requests with multiple controllers (multiple sessions, even), but they work a bit differently from controller specs. You have to use the full path (so get new_thing_path), and you can't stub anything on the controller (because there is no controller before you make a request).

See http://relishapp.com/rspec/rspec-rails/docs/request-specs/request-spec and http://api.rubyonrails.org/classes/ActionDispatch/IntegrationTest.html for more info.

like image 155
David Chelimsky Avatar answered Oct 13 '22 22:10

David Chelimsky


There is a way if you assigning the value of @controller before call test method. Example

def setup

  @controller = UserController.New

  do user stuff

  @controller = ThisController.New

  do test intented for this controller
end
like image 11
user3362168 Avatar answered Oct 14 '22 00:10

user3362168


Based on other answer, but more safe.

Store current controller instance and create a new with the required controller. Finally, replace new controller instance with the old stored instance.

def setup
  old_controller = @controller
  @controller = UserController.new

  # do user stuff

  @controller = old_controller
end
like image 5
Tomasz Nazar Avatar answered Oct 13 '22 23:10

Tomasz Nazar