簡體   English   中英

Rails Rspec 測試用例進行編輯

[英]Rails Rspec test case for edit

你好,我是 Rails 新手

我正在編寫使用 rspec gem 的測試用例

在我的 controller 中,我編輯了 function。 我有編輯 function這是我的 controller

before_action :authorize_user, only: %i[edit update destroy]
def edit
end

**private**

  def authorize_user
    id = Question.find(params[:id]).user_id
    redirect_to root_path if id != current_user.id
  end

這是我的 rspec/requests/question_rspec.rb

  describe "GET /edit" do
    before do
      sign_in(create(:user)) # Factory Bot user
    end
    it "render a successful response" do
      question = create(:question) #Factory bot question
      # question.user = current_user
      question.save
      get edit_question_url(question)
      expect(response).to be_successful
    end

  end

我收到一個錯誤,例如

Failure/Error: expect(response).to be_successful
       expected `#<ActionDispatch::TestResponse:0x00005652448f4c50 @mon_data=#<Monitor:0x00005652448f4c00>, @mon_data_..., @method=nil, @request_method=nil, @remote_ip=nil, @original_fullpath=nil, @fullpath=nil, @ip=nil>>.successful?` to be truthy, got false
     # ./spec/requests/questions_spec.rb:105:in `block (3 levels) in <main>'

誰能告訴我

我認為這與您的注釋代碼有關。

可能,這個語句id.= current_user.id是真的。 因此,要修復它,您需要將創建的用戶設置為問題,以避免在您的authorize_user回調中被重定向。

這里有一些測試用例更改:

  describe "GET /edit" do
    let!(:user) { create(:user) }

    before do
      sign_in(user) # Factory Bot user
    end

    it "render a successful response" do
      question = create(:question, user: user) #Factory bot question
      # question.save # you don't need it because the create operation already saves it
      get edit_question_url(question)
      expect(response).to be_successful
    end
  end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM