4
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!

deruse
  • 2,851
  • 7
  • 40
  • 60
  • I'm assuming you're doing this in a view spec? Because if it's a controller spec you're trying to test this will never work - rspec mocks out the view in those cases – RyanWilcox May 20 '11 at 19:20
  • Even if I say "render_views" at the top? (Yes I am doing this in a controller spec) – deruse May 20 '11 at 19:38
  • If that doesn't solve it, how would I achieve the same effect in the view spec? – deruse May 20 '11 at 19:45
  • Nvm - got it to work by scrapping stubs and implementing some helper methods in spec_helper to programatically give user different permissions. The only downside is that it makes the tests less standalone from the permissions logic. – deruse May 21 '11 at 01:46
  • Was permission_to_edit_entity? a class method on EntitiesHelper? My hunch is that it might have been an instance method that is accessible when the module gets mixed in. If that's the case, you'd have to stub that method on the mixing-in object, or figure out another approach. Sounds messy unless any_instance does the trick (which I doubt it would). – Kyle Jul 21 '11 at 21:33

1 Answers1

0

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 ...

kares
  • 7,076
  • 1
  • 28
  • 38