I want to test the following line in my view :
app/views/products/index.html.erb
<%= render @products %>
app/views/products/_product.html.erb
<td><%= distance_between(@current_location, product.location) %></td>
The @products
and @current_location
are defined in the associated controller :
def index
@products = Product.all
end
And :
unless @current_location
if !current_user.nil?
@current_location = current_user.location
else
@current_location = request.location
end
end
The distance_between
method is defined in the location helper :
def distance_between(here, there)
t('location.distance.kilometre', count: here.distance_to(there, :km).round(1))
end
So, there is my test :
let(:current_location) { request.location }
it { should have_selector('td', text: distance_between(product.location, current_location))}
And the error message :
Failure/Error: it { should have_selector('td', text: distance_between(product.location, current_location))}
NoMethodError:
undefined method `location' for nil:NilClass
Shared Example Group: "product's informations" called from ./spec/requests/product_index_page_spec.rb:119
# ./spec/requests/product_index_page_spec.rb:118:in `block (4 levels) in <top (required)>'
# ./spec/support/products/index.rb:31:in `block (2 levels) in <top (required)>'
In production, the geocoder gem can request the ip of the user, and render his location, with request.location
, but I don't know how to do that in test or development environment. Can you help me to correct my code ?