Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to keep Rails controller RSpec test DRY when introducing a private method?
    text
    copied!<p>Currently, we have one action defined within our controller, and we test it using RSpec. We now need to create a second action that needs to reuse most of the functionality contained within the first action.</p> <p>Therefore, we will refactor this common code into a private method and then have both actions call the private method.</p> <p>Question is, where do we test the functionality of this private method? Keep in mind that it is doing a lot of stuff.</p> <p>I know we should never directly test private methods, but rather test the public interface which in turn will test the private method. Surely we would want to keep our specs DRY and not repeat all common functionality specs within each 'describe', would we?</p> <p><strong>Example Class:</strong></p> <pre><code>class MyController &lt; ApplicationController def action1 ... # Do something unique to 'action1' ... my_object = ... do_some_common_stuff(my_object) end def action2 ... # Do something unique to 'action2' ... my_object = ... do_some_common_stuff(my_object) end private def do_some_common_stuff(my_object) # Do something common 1 # Do something common 2 # Do something common 3 # Do something common 4 # Do something common 5 end end </code></pre> <p><strong>Example Test Spec:</strong></p> <pre><code>describe MyController do describe "POST 'action1'" do it "should do something unique to action1" it "should do something common 1" do some_object.should_receive(:a_call) post :action1 end it "should do something common 2" it "should do something common 3" it "should do something common 4" it "should do something common 5" end describe "POST 'action2'" do it "should do something unique to action2" it "should do something common 1" do some_object.should_receive(:a_call) post :action2 end it "should do something common 2" it "should do something common 3" it "should do something common 4" it "should do something common 5" end end </code></pre> <p>As you can see this spec is not very DRY.</p> <p>Any guidance?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload