2

我是 Rails 测试的新手,我正在使用 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/ruby-1.9 .2-p290@global/gems/actionpack-3.1.3/lib/action_dispatch/testing/assertions/response.rb:67:in `assert_redirected_to'

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

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

我如何编写这样的断言来检查这些属性,检查参数是否为空。1 如何找到具有给定 id 的对象。

4

1 回答 1

1

对于功能测试,您不应该关心测试模型,即在您的情况下,您应该删除:

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

在功能测试中您想知道的是,如果页面已加载,是否正确重定向。

在您的控制器中,您对参数进行条件检查,因此对于检查的每个结果,您都编写一个测试,即您必须编写两个功能测试:

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方法。

希望这有帮助。

更新:如果您只想检查params[:app_id]GET 参数是否在 URL 中,您应该只检查此存在而不是检查它是否为空:

if params[:app_id]

else

end
于 2012-04-18T23:21:40.227 回答