【问题标题】:How to define let! with mutliple objects in Rspec test?如何定义让!在 Rspec 测试中有多个对象?
【发布时间】:2016-10-23 17:49:59
【问题描述】:

我正在练习我的 Rails 测试,现在我不知道如何解决这个问题:如何使用 let 定义多个对象!方法。它返回普通数组,而不是 ActiveRecord 关系。我想它们应该都是 ActiveRelation 关系类型才能进行比较。

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

【问题讨论】:

    标签: ruby-on-rails rspec


    【解决方案1】:

    你的 let 分配没有错!

    ActiveRecord::Relation 只是因为 Rails 使用延迟加载,有点误导。测试失败,因为您将数组粘贴在另一个数组中,导致不相等。

    将您的期望调用更改为:

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

    注意方括号的删除。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多