【问题标题】:Rails Rspec test case for edit用于编辑的 Rails Rspec 测试用例
【发布时间】:2021-01-04 12:45:22
【问题描述】:

你好,我是 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>'

谁能告诉我

【问题讨论】:

  • 只需注释掉 before_action 并再次检查,我认为 before_action 会导致此问题
  • 我删除了之前的操作。现在它成功了。但是需要使用 authorize_user 函数进行测试。
  • 只需将调试器放在他们的位置上,然后找出用户未从他们那里获得授权的原因,或者我不熟悉您使用的 santax,您能否详细说明一下这个 Question.find(params[:id]) .user_id ?

标签: rspec ruby-on-rails-5 rspec-rails ruby-on-rails-6 rspec3


【解决方案1】:

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

这句话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

【讨论】:

    猜你喜欢
    • 2013-11-07
    • 1970-01-01
    • 1970-01-01
    • 2021-12-26
    • 1970-01-01
    • 1970-01-01
    • 2012-09-26
    • 2018-03-10
    • 2012-05-17
    相关资源
    最近更新 更多