Rails Rspec 待编辑的测试用例

Rails Rspec test case for edit

你好,我是 rails

的新手

我正在编写使用 rspec gem

的测试用例

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

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