davefogo davefogo - 5 months ago 19
Ruby Question

Understanding ActiveRecord::Relations with RSpec example

I have the following ROR RSpec test:

Keep in mind that the test does pass as is in the code below. The method is correctly defined and does what is intended. The question is why when I modify and remove the [] around the @public_topic in the second example the test fails?

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


update

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

Answer

It is hard to say without seeing the implementation of visible_to.

From the first example, it looks like that method returns an ActiveRecord::Relation object. That is going to represent a collection of objects and not a single object.

So, in essence, it comes down to:

object != [object]