0

我想在我的视图中测试以下行:

应用程序/视图/产品/index.html.erb

<%= render @products %>

app/views/products/_product.html.erb

<td><%= distance_between(@current_location, product.location) %></td>

@products@current_location在关联的控制器定义:

def index
  @products = Product.all
end

和 :

unless @current_location
  if !current_user.nil?
    @current_location = current_user.location
  else
    @current_location = request.location
  end
end

distance_between方法在位置助手中定义:

def distance_between(here, there)
  t('location.distance.kilometre', count: here.distance_to(there, :km).round(1)) 
end

所以,有我的测试

let(:current_location) { request.location }
it { should have_selector('td', text: distance_between(product.location, current_location))}

和错误信息:

 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)>'

在生产中,geocoder gem 可以请求用户的 ip,并使用 渲染他的位置,request.location但我不知道如何在测试或开发环境中执行此操作。你能帮我更正我的代码吗?

4

0 回答 0