0

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 ?

Flo Rahl
  • 1,044
  • 1
  • 16
  • 33
  • Hi Flo, Are you sure you are showing us the right test ? in your test it is request.location and in your error it is current_location According to the error shown, it looks as if product is nil in your test. – NicoArbogast Sep 24 '13 at 17:46
  • OK, thanks, I corrected it (I wanted to simplify the example, but I forgot to correct the error accordingly...) – Flo Rahl Sep 25 '13 at 06:07
  • Where are you defining the product instance that you are using in distance_between(product.location ? – NicoArbogast Sep 26 '13 at 15:07
  • Hi Nico, I updated my question. – Flo Rahl Sep 30 '13 at 06:13
  • Hey, are you still stuck with this error ? In that case can you please show the whole file containing the following lines: let(:current_location) { request.location } it { should have_selector('td', text: distance_between(product.location, current_location))} – NicoArbogast Oct 10 '13 at 12:57
  • In fact, I understood where the problem was. In a development environment, I don't have a real IP address, so `request.location` can't give me a location... – Flo Rahl Oct 15 '13 at 14:16
  • Is that the whole test? Are you constructing the request somewhere? – James Dec 28 '13 at 23:09

0 Answers0