使用RSpec的post方法測試Rails控制器操作

[英]Testing a Rails controller action with RSpec’s post method


I have a very simple controller:

我有一個非常簡單的控制器:

class ThingsController < ApplicationController
  def create
    Thing.do_stuff
  end
end

…And a very simple spec:

......還有一個非常簡單的規范:

require "rails_helper"

describe ThingsController do
  describe "POST #create" do
    it "does stuff with things" do
      expect(Thing).to receive(:do_stuff)
      controller.create # This works
      post :create # This does not work
    end
  end
end

I am not running the direct invocation and the post request at the same time. Invoking the action on the controller directly passes the assertion, but invoking the action through the post method does not. It appears do_stuff is never called on Thing. Why might that be?

我沒有同時運行直接調用和post請求。在控制器上調用操作直接傳遞斷言,但通過post方法調用操作則不會。似乎do_stuff永遠不會在Thing上調用。為什么會這樣?

1 个解决方案

#1


I discovered what my issue was.

我發現了我的問題。

Invoking the controller directly keeps the spec isolated and ignores things like a before_action in the ApplicationController.

直接調用控制器會使規范保持隔離狀態,並忽略ApplicationController中的before_action之類的內容。

When we start using the post method, it’s really an integrated test and hits things like authentication. I couldn’t hit my controller method because my test user wasn’t signed in.

當我們開始使用post方法時,它實際上是一個集成測試,並且會遇到身份驗證等問題。我無法點擊我的控制器方法,因為我的測試用戶沒有登錄。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2015/05/02/7254753d0ccd4aa54ff2bc653bd4ce97.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com