2014-10-21 2 views
2

컨트롤러 테스트에서 올바른 값이 인스턴스 변수에 할당되었는지 테스트하고 있습니다.두 가지가 같을 때 RSpec eq matcher가 실패를 반환합니다.

내가 RSpec에 저를 알려줍니다

expect(assigns(:conversations)).to eq @user_inbox

작업을 수행 할 때 :

Failure/Error: expect(assigns(:conversations)).to eq @user_inbox 

    expected: #<ActiveRecord::Relation [#<Mailboxer::Conversation id: 4, subject: "Dude, what up?", created_at: "2014-10-21 08:43:50", updated_at: "2014-10-21 08:43:50">]> 
     got: #<ActiveRecord::Relation [#<Mailboxer::Conversation id: 4, subject: "Dude, what up?", created_at: "2014-10-21 08:43:50", updated_at: "2014-10-21 08:43:50">]> 

    (compared using ==) 

    Diff: 

내가 예상과 실제 사이에는 차이가없는 것을 알 수있다. 이 테스트가 실패하게 된 원인을 알고 싶습니다.

답변

4

ActiveRecord::Relation 비교 실제 관계가 아닌 결과 집합을 기반으로합니다. 예를 들어,

User.where(:id => 123) == User.where(:email => "[email protected]") 

은 false를 반환하며, 실제 쿼리가 다르기 때문에 쿼리 결과가 모두 같아도 false가 반환됩니다.

쿼리 결과가 어떻게 구성되었는지보다는 훨씬 더 신경 써야한다고 생각합니다.이 경우 to_a을 사용하여 활성 레코드 개체의 배열로 변환 할 수 있습니다. 액티브 레코드는 id 속성의 값에만 기반한 동등성을 정의합니다 (저장되지 않은 객체의 경우는 특별한 경우).

0

예, 두 개의 ActiveRecord::Relation 개체이기 때문에 가능합니다. 인스턴스 변수는 첫 번째이고 당신은 conversations

당신은 이런 일에 행이나 기타 재산의 수를 테스트해야합니다라는 또 다른 하나 만들 :

expect(assigns(:conversations).count).to eq @user_inbox.count 
0

은 어쩌면 당신은 테스트 전략을 변경해야합니다.

테스트가 잘못되었거나 테스트 전략이 잘못되었을 때. 컨트롤러 테스트에서 테스트 쿼리 결과가없는 것이 좋습니다.

당신은 당신의 쿼리 결과

describe 'GET user conversations' do 
    before do 
    your_user.stub(:conversations).and_return "foo bar"  
    end 
    it 'assigns the conversations of the user' do 
    get :user_conversation 
    expect(assigns(:conversations)).to eq your_user.conversations 
    end 
end 

조롱한다 또는 당신은 some_collaborator.should_receive 테스트해야합니다 (: some_methods)

describe 'GET user conversations' do 
    before do 
    some_collaborator.stub(:conversations) 
    end 
    it 'assigns the conversations of the user' do 
    some_collaborator.should_receive(:conversations) 
    get :user_conversation 
    end 
end 
관련 문제