简体   繁体   English

Rails Rspec 测试用例进行编辑

[英]Rails Rspec test case for edit

Hello I'm new to rails你好,我是 Rails 新手

I am writing test cases for using rspec gem我正在编写使用 rspec gem 的测试用例

In my controller I have edit function.在我的 controller 中,我编辑了 function。 I have before action for edit function This is my controller我有编辑 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

This is my rspec/requests/question_rspec.rb这是我的 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

I'm getting an error like我收到一个错误,例如

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

Could anyone please let me know谁能告诉我

I think is something related to your commented code.我认为这与您的注释代码有关。

Probably, this statement id.= current_user.id is true.可能,这个语句id.= current_user.id是真的。 So, to fix it, you need to set the created user to the question to avoid being redirected in your authorize_user callback.因此,要修复它,您需要将创建的用户设置为问题,以避免在您的authorize_user回调中被重定向。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM