1

사용자 모델의 uniquness를 테스트하고 싶습니다. 내가 bundle exec rspec를 실행 한 후 항상 다음 오류가 발생 대신에 통과rspec mongoid 유일성 검증

... 
before(:each) do 
    FactoryGirl.create(:user, email: taken_mail) 
end 

it "with an already used email" do 
    expect(FactoryGirl.create(:user, email: taken_mail)).to_not be_valid 
end 

: 같은

class User 
    include Mongoid::Document 
    field :email, type: String 
    embeds_one :details 

    validates :email, 
     presence: true, 
     uniqueness: true, 
     format: { 
     with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z0-9]{2,})\Z/i, 
     on: :create 
     }, 
     length: { in: 6..50 } 

end 

모델에 속하는 내 RSpec에 테스트가 같습니다처럼

User 모델 클래스 보인다 성공 :

Failure/Error: expect(FactoryGirl.create(:user, email: taken_mail)).to_not be_valid 
    Mongoid::Errors::Validations: 

     Problem: 
     Validation of User failed. 
     Summary: 
     The following errors were found: Email is already taken 
     Resolution: 
     Try persisting the document with valid data or remove the validations. 

성공과 함께 전달됩니다 :

it { should validate_uniqueness_of(:email) } 

나는 expect(...)을 사용하고 싶습니다. 아무도 나를 도울 수 있습니까?

+1

다음을 시도해보십시오. '(FactoryGirl.build (: user, email : taken_mail)). to_not be_valid'? – Alireza

+0

대신 build를 사용합니다. 제대로 작동하고 테스트가 통과되었지만'create' 메소드를 사용할 때 왜 에러가 발생하는지 알지 못합니다. 'FactoryGirl.create (...) '를 사용하려면 어떻게해야합니까? 대답에 남겨두면 그 점을 알려줍니다. – Mark

답변

1

expect 메서드를 사용하여 테스트하기 전에 예외가 발생하고 테스트를 중단하는 잘못된 개체를 데이터베이스에 유지하려고합니다.

올바른 방법은 create 대신 여기 build을 사용하는 것입니다.이 방법은 데이터베이스에 개체를 유지하지 않으므로 메모리에만 레코드를 작성하고 테스트를 수행 할 수 있습니다. 또한

expect(FactoryGirl.build(:user, email: taken_mail)).to_not be_valid 

그건 당신이 실제로 데이터베이스에 레코드를 저장하는 데 필요하지 않은 경우가 더 싼 작업이기 때문에, create보다는 build를 사용하는 것이 좋습니다주의와 동일한 결과를 얻을 것이다 : 따라서 문제를 해결하기 위해 , 어떤 이유로 당신의 기록이 데이터베이스에 저장되어 있어야 당신의 테스트가 원하는 방식으로 작동하지 않는 한 (예를 들어 첫 번째 기록을 저장하는 것).