用于编辑的 Rails Rspec 测试用例 [英] Rails Rspec test case for edit

查看:47
本文介绍了用于编辑的 Rails Rspec 测试用例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,我是 Rails 新手

Hello I'm new to rails

我正在编写使用 rspec gem 的测试用例

I am writing test cases for using rspec gem

在我的控制器中,我有编辑功能.我之前有编辑功能的动作这是我的控制器

In my controller I have edit function. I have before action for edit function This is my 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>'

谁能告诉我

推荐答案

我认为与您注释的代码有关.

I think is something related to your commented code.

可能,这个声明 id != current_user.id 是正确的.因此,要修复它,您需要将创建的用户设置为问题以避免在您的 authorize_user 回调中被重定向.

Probably, this statement id != current_user.id is true. So, to fix it, you need to set the created user to the question to avoid being redirected in your authorize_user callback.

这里有一些测试用例更改:

here some test case changes:

  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

这篇关于用于编辑的 Rails Rspec 测试用例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆