2012-04-06 87 views
0

更新:現在我意識到我已經誤讀了diff,並且在比較的一側有一個字符串或符號。然而,我仍然不確定我應該如何在這個測試中發揮期望。Rspec與ActiveRecord結果集匹配

我是Rspec和TDD的新手,我遇到了這個問題。我有一個控制器,這是否:

def index 
    @users = User.page(params[:page]) 
end 

(我使用Kaminara進行分頁)

而一個規範:

describe "when the user DOES have admin status" do 

    login_admin_user 
    it "should allow the user access to the complete user list page" do 
    get :index 
    response.response_code.should == 200 
    end 

    describe "and views the /users page" do 
    before(:each) do 
     User.stub(:page) {[ mock_model(User), mock_model(User), mock_model(User) ]} 
    end 

    it "should show all users" do 
    get :index 
    assigns (:users).should =~ User.page 
    end 
    end 

end 

該規範失敗,出現以下:

Failure/Error: assigns (:users).should =~ User.page 
    expected: [#<User:0x5da86a8 @name="User_1004">, #<User:0x5d9c90c @name="User_1005">, #<User:0x5d93ef6 @name="User_1006">] 
     got: :users (using =~) 
    Diff: 
    @@ -1,4 +1,2 @@ 
    -[#<User:0x5da86a8 @name="User_1004">, 
    - #<User:0x5d9c90c @name="User_1005">, 
    - #<User:0x5d93ef6 @name="User_1006">] 
    +:users 

這些結果集看起來完全相同。爲什麼此規格失敗?提前致謝!

回答

0

我認爲問題是assigns之後的空間。它將符號:users與您的列表進行比較。將其更改爲:

assigns(:users).should =~ User.page 

而只是如何讀Rspec的故障的說明。 expected之後的部分是您給should的部分,而got之後的部分是您的代碼實際生成的值。所以從報告中可以清楚地看出結果集不相同。

+0

是的,這是破解它。謝謝! – theflyingbrush 2012-04-06 15:08:40