djburdick
djburdick

Reputation: 11950

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

Upvotes: 29

Views: 17394

Answers (3)

Tomasz Nazar
Tomasz Nazar

Reputation: 448

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

Upvotes: 5

user3362168
user3362168

Reputation: 157

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

Upvotes: 12

David Chelimsky
David Chelimsky

Reputation: 9000

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.

Upvotes: 32

Related Questions