用于编辑的Rails Rspec测试用例

用于编辑的Rails Rspec测试用例,rspec,ruby-on-rails-5,rspec-rails,ruby-on-rails-6,rspec3,Rspec,Ruby On Rails 5,Rspec Rails,Ruby On Rails 6,Rspec3,你好,我是rails的新手 我正在编写使用rspecgem的测试用例 在我的控制器中,我有编辑功能。我有编辑功能的前操作 这是我的控制器 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

你好,我是rails的新手

我正在编写使用rspecgem的测试用例

在我的控制器中,我有编辑功能。我有编辑功能的前操作 这是我的控制器

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\u 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>'

失败/错误:期望(响应)。成功
期望“成功”是真的,是假的
#./spec/requests/questions_spec.rb:105:in'block(3层)in'

任何人都可以让我知道

我认为这与您评论的代码有关

很可能,此语句
id!=当前_user.id
为真。因此,要解决这个问题,您需要将创建的用户设置为问题,以避免在
authorize\u 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

只需在行动前进行评论并再次检查,我认为行动前会导致这种情况。我删除了行动前的。现在它成功了。但是使用authorize_user函数进行测试是必要的。只需将调试器放入调试器,然后查找用户未从其进行授权的原因,或者我不熟悉您正在使用的santax。请详细说明此问题。find(params[:id])。user_id?