通过 RSpec 示例了解 ActiveRecord::Relations

Understanding ActiveRecord::Relations with RSpec example

我有以下 ROR RSpec 测试:

请记住,测试确实通过了,如下面的代码所示。该方法已正确定义并按预期执行。问题是为什么当我在第二个例子中修改和删除 @public_topic 周围的 [] 时,测试失败了?

describe "scopes" do
    before do
      @public_topic = Topic.create!(name: RandomData.random_sentence, description: RandomData.random_paragraph)
      @private_topic = Topic.create!(name: RandomData.random_sentence, description: RandomData.random_paragraph, public: false)
    end

    describe "visible_to(user)" do
      it "returns all topics if user is present" do
          user = User.new
          expect(Topic.visible_to(user)).to eq(Topic.all)
      end
      it "returns only public topics if user is nil" do
        expect(Topic.visible_to(nil)).to eq([@public_topic])
      end
    end
  end

更新

scope :visible_to, -> { where(public: true) }

没有看到 visible_to 的实现很难说。

从第一个示例来看,该方法 returns 看起来像是一个 ActiveRecord::Relation 对象。这将表示对象的集合而不是单个对象。

所以,从本质上讲,它归结为:

object != [object]