2011-08-30 188 views
0

我正在写使用Rails 3应用程序在我的功能测试,测试/功能/ cust_infos_controller_test.rb,我有这些:的Rails 3控制器测试

require 'test_helper' 

class CustInfosControllerTest < ActionController::TestCase 
    # Replace this with your real tests. 
    test "should get cust" do 
    get :customerinfo 
    assert_response :success 
    assert_not_nil assigns("cust_infos") 
    end 
end 

我的控制器是非常简单的,因为它只是发现客户的所有信息:

class CustInfosController < ApplicationController 
    def customerinfo 
    @cust_info = CustInfo.find(:all, :order=>"cust_id") 
    @cust_info.each do |ci|            
     if ci.upload_freq == 'W' 
     ci.upload_freq = 'Weekly' 
     elsif ci.upload_freq == 'M' 
     ci.upload_freq = 'Monthly' 
     end 
    end 
    end 
end 

当我运行它:

$ ruby -Itest test/functional/cust_infos_controller_test.rb 

我得到了以下ERR或:

Loaded suite test/functional/cust_infos_controller_test 
Started 
E 
Finished in 0.025258 seconds. 

1) Error: 
test_should_get_cust(CustInfosControllerTest): 
ActiveRecord::StatementInvalid: PGError: ERROR: numeric field overflow 
DETAIL: A field with precision 4, scale 0 must round to an absolute value less than 10^4. 

: INSERT INTO "cust_infos" ("cust_id") VALUES (298486374) 


1 tests, 0 assertions, 0 failures, 1 errors 

在我cust_infos表,我已经CUST_ID为整数。但是我不知道为什么当我运行控制器测试来获取一些记录时,活动记录会执行插入语句。我该如何解决?

更新:我注释掉了customerinfo方法中的所有行,并运行相同的测试。得到完全相同的结果。所以我猜这不是我的方法行为,而是Rails?任何提示?

+0

您可以发布您的customerinfo方法吗? –

+0

我刚发布了它。它使用activerecord查找所有客户。就是这样。视图将显示结果。 – swingfuture

回答

0

我明白你在做什么。你需要做的是为你的观点创建一个帮手。

application_helper.rb

def display_upload_freq(s) 
    case s 
    when 'W' 
    'Weekly' 
    when 'M' 
    'Monthly' 
    end 
end 

cust_info_controller.rb

class CustInfosController < ApplicationController 
    def customerinfo 
    @cust_info = CustInfo.find(:all, :order=>"cust_id") 
    end 
end 

然后在您的视图时,您将可以通过@cust_info迭代,对于upload_freq,使用dislay_upload_freq(ci.upload_freq)。假设你有@ cust_info.each do | ci |。然后,你不会混淆数据库和保存任何东西。

+0

我试图显示这个属性与db中的属性不同。我没有保存它,因为数据库不需要更改。我想我可以建立另一个模型来做到这一点。但认为这只是一个属性。 – swingfuture

+0

更改了满足您需求的答案。 =) –

+0

好的。这是一个很好的做法。虽然它仍然没有解决我的测试问题。 – swingfuture

0

您是否使用工厂或灯具来创建测试数据?如果不是,你是如何创建它的?我的猜测是插入是在您设置测试数据时发生的,而不是因为您的控制器发生任何事情。这一猜测的第二部分是由于注释掉控制器中的所有代码没有摆脱错误这一事实。

0

我知道这篇文章是相当古老的,但我会张贴我的答案,以防有人被搜索引擎带到这里。 我有完全相同的问题,问题来自test/fixtures/{name_of_your_model} .yml中的夹具文件。 Rails添加在这个文件中的一些初始值,在我的情况是这样的:

one: {} 
# column: value 
# 
two: {} 
# column: value 

,当你想运行测试,它会尝试创建一个使用这种灯具的测试数据库。这就是问题发生的地方。试图创建一个空记录,而您不允许您的表中有空ID。

删除这些灯具或填充适当的值应该可以解决问题。