Rspec / Capybara: Testing if a controller method is called

末鹿安然 提交于 2019-12-03 09:13:05

I'm not sure exactly what you want to test, and I think there's some confusion as to what methods can be used where, so I'll try and give examples of Routing specs, Request Specs, Controller specs, and Feature specs, and hopefully one of them will be appropriate for you.

Routing

If you want to make sure that your root path gets routed to the home#index action, a routing spec may be appropriate:

spec/routing/routing_spec.rb

describe "Routing" do
  it "routes / to home#index" do
    expect(get("/")).to route_to("home#index")
  end
end

Request

If you want to make sure that the index template gets rendered on a request to your root path, a request spec may be appropriate:

spec/requests/home_requests_spec.rb

describe "Home requests" do
  it 'successfully renders the index template on GET /' do
    get "/"
    expect(response).to be_successful
    expect(response).to render_template(:index)
  end
end

Controller

If you want to make sure that the index template gets rendered on a request to the index action of your HomeController, a controller spec may be appropriate (and quite similar to a request spec in this case, but focused exclusively on the controller):

spec/controllers/home_controller_spec.rb

describe HomeController do
  describe "GET index" do
    it "successfully renders the index template" do
      expect(controller).to receive(:index) # this line probably of dubious value
      get :index
      expect(response).to be_successful
      expect(response).to render_template(:index)
    end
  end
end

Feature

If you want to make sure the page rendered by home#index has some specific content, a feature spec may be appropriate (and also the only place you can use Capybara methods like visit, depending on your Rails/RSpec version):

spec/features/home_features_spec.rb

feature "Index page" do
  scenario "viewing the index page" do
    visit root_path
    expect(page).to have_text("Welcome to my awesome index page!")
  end
end
class MyController < ApplicationController
  def index
    my_method
  end

  def my_method
  end
end

describe MyController do
  it 'calls my method' do
    expect(controller).to receive(:my_method)

    get :index
  end
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!