2016-10-23 15 views
0

我正在練習我的Rails測試,現在我不知道如何解決這個問題:如何使用let定義多個對象!方法。它返回正常的數組,而不是ActiveRecord關係。我猜他們應該都是ActiveRelation關係類型才能比較。如何定義let!多重對象在Rspec測試?

require 'rails_helper' 

RSpec.describe PostsController do 

    let!(:posts) do 
     [Post.create(title: "Title 1", body: "Body 1"), Post.create(title: "Title 2", body: "Body 2")] 
    end 

    describe "posts" do 
    it "assigns @posts" do 

     get :index 
     expect(assigns(:posts)).to eq([posts]) 
    end 
    end 

end 

運行測試後:

PostsController 
    posts 
    assigns @posts (FAILED - 1) 

Failures: 

    1) PostsController posts assigns @posts 
    Failure/Error: expect(assigns(:posts)).to eq([posts]) 

     expected: [[#<Post id: 1, title: "Title 1", body: "Body 1", created_at: "2016-10-23 05:40:39", updated_at: "201...: "Title 2", body: "Body 2", created_at: "2016-10-23 05:40:39", updated_at: "2016-10-23 05:40:39">]] 
      got: #<ActiveRecord::Relation [#<Post id: 1, title: "Title 1", body: "Body 1", created_at: "2016-10-23 05:...: "Title 2", body: "Body 2", created_at: "2016-10-23 05:40:39", updated_at: "2016-10-23 05:40:39">]> 

     (compared using ==) 

     Diff: 
     @@ -1,3 +1,13 @@ 
     -[[#<Post id: 1, title: "Title 1", body: "Body 1", created_at: "2016-10-23 05:40:39", updated_at: "2016-10-23 05:40:39">, 
     - #<Post id: 2, title: "Title 2", body: "Body 2", created_at: "2016-10-23 05:40:39", updated_at: "2016-10-23 05:40:39">]] 
     +[#<Post:0x000000063ef570 
     + id: 1, 
     + title: "Title 1", 
     + body: "Body 1", 
     + created_at: Sun, 23 Oct 2016 05:40:39 UTC +00:00, 
     + updated_at: Sun, 23 Oct 2016 05:40:39 UTC +00:00>, 
     + #<Post:0x000000063ef228 
     + id: 2, 
     + title: "Title 2", 
     + body: "Body 2", 
     + created_at: Sun, 23 Oct 2016 05:40:39 UTC +00:00, 
     + updated_at: Sun, 23 Oct 2016 05:40:39 UTC +00:00>] 

    # ./spec/controllers/posts_controller_spec.rb:13:in `block (3 levels) in <top (required)>' 

Finished in 0.43037 seconds (files took 2.4 seconds to load) 
1 example, 1 failure 

Failed examples: 

rspec ./spec/controllers/posts_controller_spec.rb:10 # PostsController posts assigns @posts 

回答

1

沒有什麼不對您的任務支持讓!

ActiveRecord :: Relation只是因爲Rails使用延遲加載並且有點誤導。該測試失敗,因爲您將數組粘貼到另一個數組中,導致不平等。

更改您的期望來電:

expect(assigns(:posts)).to eq(posts) 

注意去除方括號。