2017-10-30 4 views
0

사용자의 제목이 저장되는지 확인하는 레일스 통합 테스트를 작성하고 있습니다. 제목은 하나의 유효성 검사가 있습니다. 255자를 넘지 않아야합니다. 그러나 @user.update_attributes!(title: params[:title])에서 "비밀번호는 6 자 이상이어야합니다."라는 오류가 발생합니다. 하지만 ... 난 비밀 번호 또는 제목 이외의 아무것도 업데이 트하지 않을거야. 그렇다면이 속성을 자체 유효성 검사로 저장하고 암호에 대해 걱정하지 않으려면 어떻게해야합니까?(Rails) update_attributes가 비밀번호를 사용하지 않는 통합 테스트 중에 오류가 발생했습니다.

테스트 :

test "profile submits new title and description successfully" do 
    log_in_as(@non_admin) 
    get user_path(@non_admin) 
    assert_nil @non_admin.title 
    post "https://stackoverflow.com/users/#{@non_admin.id}/update_description", 
     { title: "I am a man of constant sorrow." } 
    user = assigns(:user) 
    user.reload.title 
    assert user.title == "I am a man of constant sorrow." 
    assert_template 'users/show' 
    assert flash[:success] 
    end 

컨트롤러 방법 (완료되지,하지만 당신은 아이디어를 얻을 수 있습니다). 암호 확인 오류가 발생하는 것은 update_attributes! 호출입니다.

# Handles user's posted title and description. 
    def update_description 
    @user = User.find(params[:id]) 
    # Check if title is present. If so, attempt to save, load flash, and reload. 
    if @user.update_attributes!(title: params[:title]) 
     flash[:success] = "Saved title. " 
    # if unable, set error flash and reload. 
    else 
     flash[:warning] = "Unable to save." 
    end 
    # Same logic as before, now for description. 
    # Make sure two different [:success] flashes work! Probably not! 
    redirect_to user_path(@user) 
    end 

하는 검증 :

archer: 
    name: Sterling Archer 
    email: [email protected] 
    password_digest: <%= User.digest('Jsdfuisd8f') %> 
    activated: true 
    activated_at: <%= Time.zone.now %> 

I :

경우
23:08:51 - INFO - Running: test/integration/users_show_test.rb 
Started 
ERROR["test_profile_submits_new_title_and_description_successfully", UsersShowTest, 2017-10-23 01:06:11 -0400] 
test_profile_submits_new_title_and_description_successfully#UsersShowTest (1508735171.57s) 
ActiveRecord::RecordInvalid:   ActiveRecord::RecordInvalid: Validation failed: Password must have at least 6 characters 
      app/controllers/users_controller.rb:71:in `update_description' 
      test/integration/users_show_test.rb:22:in `block in <class:UsersShowTest>' 
     app/controllers/users_controller.rb:71:in `update_description' 
     test/integration/users_show_test.rb:22:in `block in <class:UsersShowTest>' 

그것이 여기 @non_admin로로드 고정 장치가 관련이있어 : 여기

validates :password, length: { minimum: 6, 
           message: "must have at least 6 characters" } 
    validates :title, length: { maximum: 255 } 

테스트 오류입니다 'm a Ra ils noob 그래서 아마 뭔가 기본. 미리 감사드립니다 ...

업데이트 : 아래 kasperite 토론을 참조하십시오. 비밀번호 확인에 on: create을 추가하기 만하면되었습니다.

답변

1

update_attributes!을 호출하면 save!이 트리거되어 모델에서 유효성 검사가 트리거됩니다. 그리고 암호를 제공하지 않으므로 예외가 발생합니다.

당신은 할 수 있습니다 update_attribute(:title, params[:title])하는 바이 패스 검증 나이 :

@user.title = params[:title] 
    @user.save!(validation: false) 

참조 : 답장을 http://api.rubyonrails.org/classes/ActiveRecord/Persistence.html#method-i-update-21

+0

감사합니다! 문제는 특별히이 유효성 검사를 트리거하려는 것이지만이 특성에 대해서만입니다. 나는'update_attributes! '가'save!'를 유발한다는 것을 안다. (데이터베이스에 저장하고 싶다. 관련 검증 만 사용하는 방법이 있습니까? 아마도 통합 테스트를 수행하기 위해 조명기를 다르게 준비해야합니까? 위의 조명기를 보여 드리겠습니다 (아마도 적합할까요?). – globewalldesk

+1

유효성 검사를 트리거하는시기를 제어하는 ​​유일한 방법은 모델 (http://guides.rubyonrails.org/active_record_validations.html#on)에 있습니다. 원하는대로 가정합니다. – kasperite

+0

확인해 보겠습니다. 그걸 완전히 수정 :'validates : 암호, 길이 : {최소 : 6, 메시지 : 6 자 이상이어야합니다.}} create' 간단합니다. 고마워 친구! – globewalldesk

관련 문제