rspec希望在嵌套块中更改闪存失败

时间:2013-07-29 20:50:55

标签: error-handling rspec flash-message

我正在使用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]消息放在第一个块中,并且工作正常。只有当它嵌套在第二个块中时它才会失败。我自己测试了它,闪光灯[:成功]正如我所期望的那样出现。

1 个答案:

答案 0 :(得分: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