1

I have user model, query helper and a controller : the helper contain a method that return a list of user when send a search query request from the view:

class UserQueryHelper

  def initialize( query = nil )
    @query = Arel.sql("UNACCENT('%#{ query }%')")
  end

  def search
    User.where( first_name.matches( @query ).or( last_name.matches( @query ) ))
  end

protected

  def users   ; User.arel_table   ; end

  def first_name
    Arel::Nodes::NamedFunction.new( "UNACCENT", [ users[ :first_name ] ] )
  end

  def last_name
    Arel::Nodes::NamedFunction.new( "UNACCENT", [ users[ :last_name ] ] )
  end

end

in the model I call that helper :

def self.search( query )
    if query.present?
      UserQueryHelper.new( query ).search
    else
      all
    end
end 

and in the controller I get the list of user searched by the admin :

users_to_export = User.regular.search(params[:search]).includes( :company )

I want to write some unit test for this and I didn't got the right way to do it and I tried this code but it doesn't work :

  require 'spec_helper'

describe UserQueryHelper do

  let!( :query ) { UserQueryHelper.new( "sahnoun" ) }
  it "return user" do
    user1 = create :user, first_name: "sahnoun", last_name: "mabrouk", company: $company
    expect( query.send( :search ) ).to include user1

  end

end
1
  • Are you testing the search method or the initialize method? shouldn't you have separate tests for each of them? Commented May 8, 2018 at 9:46

1 Answer 1

2

You must be getting an error stack level too deep

let!( :query ) { UserQueryHelper.new( query ) }

is executing as

UserQueryHelper.new( UserQueryHelper.new (UserQueryHelper.new (....)))

it should be defined as

let!( :query ) { UserQueryHelper.new( "<Your Test Query>" ) }
Sign up to request clarification or add additional context in comments.

10 Comments

Thanks ayush for your comment , yes that's exactly the error i got, so in "<Your Test Query>" should i write a query like : "User.where( first_name.matches( user1.first_name ).or( last_name.matches( user1.last_name ) ))" ?
@noun7 probably not because it should be pure SQL, but consider this could be dangerous if the query can be constructed by a user.
you can try UserQueryHelper.new( "sahnoun" ) since you are later creating a test user with this name (sahnoun). Your test will pass.
I did like you said but it didn't pass !
send me the output puts query.send( :search )
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.