I have a photo model with the following method for finding related tags by name:
class Photo < ActiveRecord::Base
has_many :taggings, :dependent => :destroy
has_many :tags, :through => :taggings
...
def self.tagged_with( string )
array = string.split(',').map{ |s| s.lstrip }
joins(:tags).where('tags.name' => array ).group(:id)
end
...
end
If I use this in the console, it gives what I expect:
Photo.tagged_with('foo, bar, baz')
However, I tried to build this using a test in RSpec, and the test failed. Here is my test:
describe "tags" do
it "should return a list of photos matching a string of tags" do
t1 = Tag.create(:name=>'test')
t2 = Tag.create(:name=>'bar')
t1.photos << Photo.find(1,2,3)
t2.photos << Photo.find(3,4)
t1.save
t2.save
Photo.tagged_with('test').should have(3).photos
Photo.tagged_with('bar').should have(2).photos
Photo.tagged_with('test, bar').should have(4).photos
end
end
This test fails with the following error:
1) Photo tags should return a list of photos matching a string of tags
Failure/Error: Photo.tagged_with('test').should have(3).photos
ActiveRecord::StatementInvalid:
SQLite3::SQLException: ambiguous column name: id: SELECT COUNT(*) AS count_all, id AS id FROM "photos" INNER JOIN "taggings" ON "photos"."id" = "taggings"."photo_id" INNER JOIN "tags" ON "tags"."id" = "taggings"."tag_id" WHERE "tags"."name" IN ('test') GROUP BY id
So, the code works, but the test fails. What am I doing wrong in my test?
source
share