0

我正在使用 ActiveAdmin,并且我有一个控制器需要在我的模型中调用 2 个方法。这两种模型方法都可能在失败时引发错误,因此我将控制器设置为仅在第一个成功时才调用第二个。例如:

member_action :controller_method, :method => :post do
  begin
    model.method_1!
  rescue => e
    flash[:error] = "Method1 failed with error #{e}"
  else
    begin
      model.method_2!
    rescue => e
      flash[:error] "Method1 was successful but Method2 failed with error #{e}"
    else
      flash[:success] = "Method1 and Method 2 were successful."
    end
  end
end

我的测试看起来像这样:

it "flashes success" do
  expect { post "method1_and_method2" }.to change { flash[:success] }
end

我尝试将 flash[:success] 消息放在第一个块中,效果很好。只有当它嵌套在第二个块中时才会失败。我自己测试过它,并且 flash[:success] 正在按我的预期出现。

4

1 回答 1

0

好的,我需要模拟出控制器实例变量,并指定它为这两种方法接收并返回 true。这是通过测试的样子:

before do
  Model.should_receive(:find_by_id).and_return(model)
end

it "flashes success" do
  model.should_receive(:method_1!).and_return(true)
  model.should_receive(:method_2!).and_return(true)
  expect { post "method1_and_method2" }.to change { flash[:success] }
end
于 2013-07-29T21:00:44.370 回答