1

我是 Rails 的新手,我遇到了一个功能测试的问题,该测试因未定义的方法而失败:

1) Error:
test_should_get_index(OrdersControllerTest):
ActionView::Template::Error: undefined method `name' for nil:NilClass
app/views/orders/index.html.erb:19:in `_app_views_orders_index_html_erb__2011622583_2177866460_0'
app/views/orders/index.html.erb:14:in `_app_views_orders_index_html_erb__2011622583_2177866460_0'
app/controllers/orders_controller.rb:8:in `index'
/test/functional/orders_controller_test.rb:9:in `test_should_get_index'

在浏览器中一切正常,只是测试失败。

这是views/orders/index.html.erb文件内容:

<% @orders.each do |order| %>
<tr>
 <td><%= order.name %></td>
 <td><%= order.address %></td>
 <td><%= order.email %></td>
 <td><%= order.pay_type.name %></td>

Pay_type是另一个包含支付类型名称的表;在订单表中有一个外键叫做pay_type_id. 在浏览器中,我正确看到了带有order.pay_type.name语句的支付类型名称,但功能测试失败。

test_should_get_index:

 test "should get index" do
   get :index
   assert_response :success
   assert_not_nil assigns(:orders)
 end

订购夹具:

one:
  name: Dave Thomas
  address: MyText
  email: dave@example.org
  pay_type_id: 1

two:
  name: MyString
  address: MyText
  email: MyString
  pay_type_id: 1

paytypes 固定装置:

one:
  id: 1
  name: Check

two:
  id: 2
  name: Credit Card

three:
  id: 3
  name: Purchase Order

*订单控制器:*

def index
@orders = Order.paginate :page=>params[:page], :order=>'created_at desc',
  :per_page => 10

respond_to do |format|
  format.html # index.html.erb
  format.xml  { render :xml => @orders }
end
end

有人可以帮助我吗?

raise Exception.new(@orders.inspect)在视图中添加了以下错误:

`1) Error:
test_should_get_index(OrdersControllerTest):
ActionView::Template::Error: [#<Order id: 298486374, name: "MyString", address: "MyText", email: "MyString", created_at: "2013-02-12 14:05:11", updated_at: "2013-02-12 14:05:11", pay_type_id: 1>, #<Order id: 980190962, name: "Dave Thomas", address: "MyText", email: "dave@example.org", created_at: "2013-02-12 14:05:11", updated_at: "2013-02-12 14:05:11", pay_type_id: 1>]
app/views/orders/index.html.erb:14:in `_app_views_orders_index_html_erb__1955286768_2214618420_0'
app/controllers/orders_controller.rb:8:in `index'
/test/functional/orders_controller_test.rb:9:in `test_should_get_index'`
4

1 回答 1

0

@orders 中有一些东西是 nil,当你调用name它时,它会给出错误。确保 @orders 仅包含订单,并且在测试时不包含 nil。

于 2013-02-12T13:36:14.203 回答