Rspec / Capybara:测试是否调用控制器方法
鉴于我设置了一个带有索引动作的HomeController
class HomeController < ApplicationController def index @users = User.all end end
并通过根路径路由到它,
root :to => "home#index"
为什么这个请求规范失败了
it 'should called the home#index action' do HomeController.should_receive(:index) visit root_path end
以下消息
Failure/Error: HomeController.should_receive(:index) ().index(any args) expected: 1 time received: 0 times
? 是因为索引方法被调用为实例方法而不是类方法?
我不确定你想要测试什么,我认为在哪里可以使用哪些方法存在一些混淆,所以我将尝试提供路由规范 , 请求规范 , 控制器规范和function规范的示例,以及希望其中一个适合你。
路由
如果要确保将根路径路由到home#index
操作,则路由规范可能是合适的:
规格/路由/ routing_spec.rb
describe "Routing" do it "routes / to home#index" do expect(get("/")).to route_to("home#index") end end
请求
如果要确保在对根路径的请求中呈现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
调节器
如果你想确保index
模板是在对HomeController
的index
操作的请求中呈现的,那么控制器规范可能是合适的(在这种情况下非常类似于请求规范,但只专注于控制器):
规格/控制器/ 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
特征
如果你想确保home#index
#index呈现的页面有一些特定的内容,那么function规范可能是合适的(也是唯一可以使用Capybara方法的地方,例如visit
,具体取决于你的Rails / RSpec版本):
规格/function/ 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