2

我是rails新手,我正在使用unit:test。我有一个动作在我的控制器如何在rails 3.1和unit中编写功能测试用例:test

def save_campaign 
     unless params[:app_id].blank? 
     @app = TestApp.find(params[:app_id]) 
      if params[:test_app] 
      @app.update_attributes(params[:test_app]) 
      end 
     flash[:notice] = "Your Registration Process is completed" 
     redirect_to "/dashboard" 
     else 
    redirect_to root_path 
    end 
    end 

和我的测试情况如下

test "should save campagin " do 
assert_difference('TestApp.count', 0) do 
      post :save_campaign, test_app: @test_app.attributes 
     end 
     assert_redirected_to "/dashboard" 
     end 
    end 

这种方法是POST方法。当运行这个测试,它失败并显示我的消息

“应该保存campagin(0.07s) 期望的回应是一个重定向到http://test.host/dashboard但被重定向到http://test.host/ /home/nouman/.rvm /gems/[email protected]/gems/actionpack-3.1.3/lib/action_dispatch/testing/assertions/response.rb:67:in`assert_redirected_to”

我的猜测是,我我没有给它正确的断言检查参数

params [:app_id]和@app = TestApp.find(params [:app_id])。

我该如何编写这样的断言来检查这些属性,检查一个参数是否为空。如何找到一个给定ID的对象。

回答

1

对于功能测试,你不应该在乎测试模型,这是你的情况,你应该删除:

assert_difference('TestApp.count', 0) do 
.. 
end 

要在功能测试就知道那是什么,如果页面加载,正确重定向。

在你的控制器,你有PARAMS条件检查,所以对于每个检查的结果如何,你写测试中的每个,那就是你必须写两个功能测试:

test "if app_id param is empty, #save_campaign redirect to root" do 
    post :save_campaign, :app_id => nil 
    assert_redirected_to root_path 
end 

test "#save_campaign" do 
    post :save_campaign, :app_id => app_fixture_id, :test_app => @test_app.attributes.to_params 
    assert_redirected_to '/dashboard' 
end 

的诀窍准备后的参数是使用方法to_params的方法。

希望得到这个帮助。

UPDATE:如果你只是想检查是否params[:app_id] GET参数是在URL中,你应该检查该存在的,而不是检查,如果它是不是空白:

if params[:app_id] 

else 

end 
+0

感谢忠为回答,对不起,我没有意识到你的回应,这就是为什么在几个月后接受它。 – user1014473 2012-08-03 11:21:21

相关问题