Rspec/Capybara:测试是否调用控制器方法

use*_*332 4 controller rspec ruby-on-rails capybara

鉴于我设置了一个带有索引动作的HomeController

class HomeController < ApplicationController
  def index
    @users = User.all
  end
end
Run Code Online (Sandbox Code Playgroud)

并通过根路径路由到它,

  root :to => "home#index"
Run Code Online (Sandbox Code Playgroud)

为什么这个请求规范失败了

it 'should called the home#index action' do
    HomeController.should_receive(:index)
    visit root_path
end
Run Code Online (Sandbox Code Playgroud)

以下消息

 Failure/Error: HomeController.should_receive(:index)
   (<HomeController (class)>).index(any args)
       expected: 1 time
       received: 0 times
Run Code Online (Sandbox Code Playgroud)

?是因为索引方法被调用为实例方法而不是类方法?

Pau*_*nti 23

我不确定你想要测试什么,我认为在哪里可以使用哪些方法存在一些混淆,所以我将尝试提供路由规范,请求规范,控制器规范功能规范的示例,以及希望其中一个适合你.

路由

如果要确保将根路径路由到home#index操作,则路由规范可能是合适的:

规格/路由/ routing_spec.rb

describe "Routing" do
  it "routes / to home#index" do
    expect(get("/")).to route_to("home#index")
  end
end
Run Code Online (Sandbox Code Playgroud)

请求

如果要确保index模板是根据对根路径的请求呈现的,请求规范可能是合适的:

规格/请求/ 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
Run Code Online (Sandbox Code Playgroud)

调节器

如果您想确保index模板是在index对您的操作的请求中呈现的HomeController,那么控制器规范可能是合适的(在这种情况下非常类似于请求规范,但仅专注于控制器):

规格/控制器/ 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
Run Code Online (Sandbox Code Playgroud)

特征

如果你想确保被渲染的页面home#index有一些具体的内容,功能规格可适当(也是唯一的地方,你可以使用水豚的方法一样visit,这取决于你的Rails/RSpec的版本):

规格/功能/ 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
Run Code Online (Sandbox Code Playgroud)