Reputation: 53
I'm new to RSpec so this really give me a headache. I have a search by keyword or by category in Post model:
def self.search(search, category_id)
if search.strip.empty?
[]
elsif category_id.empty?
Post.approved.where('lower(title) LIKE ?', "%#{search.downcase.strip}%")
else
@category = Category.find_by('id = ?', category_id.to_i)
@category.posts.approved.where('lower(title) LIKE ?', "%#{search.downcase.strip}%")
end
end
I know how to write test for easy thing like validations and associations, but I still can not figure how to write test for this class method. Any help is appreciated.
Upvotes: 0
Views: 136
Reputation: 114248
You could create some test data:
let!(:post_1) { Post.create(title: 'some example title') }
let!(:post_2) { Post.create(title: 'another title') }
And validate that your search returns the correct records for various search terms, e.g.:
expect(Post.search('example')).to contain_exactly(post_1)
expect(Post.search('EXAMPLE')).to contain_exactly(post_1)
expect(Post.search('title')).to contain_exactly(post_1, post_2)
expect(Post.search('foo')).to be_empty
(assuming search
is a method of Post
)
Upvotes: 1