使用 mocha 打桩助手

发布于 2024-11-08 22:08:05 字数 552 浏览 0 评论 0原文

it "should have edit button if user has permission to edit" do
  EntitiesHelper.stubs(:permission_to_edit_entity?).returns(true)
  get :index
  @entities[0..3].each do |entity|
    response.should have_selector("form",
      :method => "get",
      :action => "/entities/edit/#{entity[:id]}") do |form|
        form.should have_selector("input", :value => "Edit")
    end
  end
end

我正在尝试编写一个简单的测试用例,用于测试用户是否有权编辑是否显示编辑按钮。我正在尝试为此使用存根。然而,它似乎不起作用。如果存根有效,输出视图不会在每个实体旁边显示我所期望的编辑按钮。我是摩卡和存根的新手 - 我在这里做错了什么?

谢谢!

it "should have edit button if user has permission to edit" do
  EntitiesHelper.stubs(:permission_to_edit_entity?).returns(true)
  get :index
  @entities[0..3].each do |entity|
    response.should have_selector("form",
      :method => "get",
      :action => "/entities/edit/#{entity[:id]}") do |form|
        form.should have_selector("input", :value => "Edit")
    end
  end
end

I am trying to write a simple test case which tests that an edit button is showed if the user has permission to edit. I am trying to use stubbing for this. However, it doesn't seem to work. The output view does not show the edit button next to every single entity which I would expect if the stubbing works. I am new to mocha and stubbing - I am doing something wrong here?

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

·深蓝 2024-11-15 22:08:05

我假设 EntitiesHelper 是一个普通的旧 Rails 助手,它混合到控制器中 - 因此它的所有实例方法(例如permission_to_edit_entity? )都可供控制器使用,并且视图具有访问这些辅助方法(通过控制器)...所以您可以在控制器上存根该方法:

controller.stubs(:permission_to_edit_entity?).returns(true)

在这种特殊情况下,我什至会考虑将存根更改为模拟,因为您希望调用该方法(尽管您是测试按钮的存在,很高兴知道流程没有按预期发生):

controller.expects(:permission_to_edit_entity?).returns(true)

但这当然是有争议的,无论如何你都应该没问题......

I assume EntitiesHelper is a plain-old rails helper that gets mixed into the controller - thus all it's instance methods (such as permission_to_edit_entity?) are available to the controller and views have access to these helper methods (via the controller) ... so You might stub the method on the controller :

controller.stubs(:permission_to_edit_entity?).returns(true)

in this particular case I would even consider changing the stub to mock since You expect the method to be called (although You're testing the button presence, it's good to know that the flow did not happen as expected) :

controller.expects(:permission_to_edit_entity?).returns(true)

but this of course is debatable and You should be fine either way ...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文