Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
| 1 | <?php |
||
| 5 | class WidgetTest extends TestCase |
||
| 6 | { |
||
| 7 | public function test_presenter_method_is_called_with_data_from_controller() |
||
| 8 | { |
||
| 9 | View::shouldReceive('exists')->once()->andReturn(true); |
||
| 10 | View::shouldReceive('make')->once()->with('hello', ['data' => 'barfoo'], [])->andReturn(app('view')); |
||
| 11 | View::shouldReceive('render')->once()->andReturn('<br>'); |
||
| 12 | |||
| 13 | //act |
||
| 14 | $widget = new Widget5(); |
||
| 15 | render_widget($widget); |
||
| 16 | } |
||
| 17 | |||
| 18 | public function test_default_view_name_is_figured_out_correctly() |
||
| 19 | { |
||
| 20 | View::shouldReceive('exists')->once()->andReturn(true); |
||
| 21 | View::shouldReceive('make')->once()->with('Widgets::Foo.Widget1View', ['data' => 'foo'], [])->andReturn(app('view')); |
||
| 22 | View::shouldReceive('render')->once()->andReturn('<br>'); |
||
| 23 | \App::shouldReceive('call')->once()->andReturn('foo'); |
||
| 24 | |||
| 25 | //act |
||
| 26 | $widget = new \App\Widgets\Foo\Widget1(); |
||
| 27 | render_widget($widget); |
||
| 28 | } |
||
| 29 | |||
| 30 | public function test_context_as_is_passes_to_view_correctly() |
||
| 31 | { |
||
| 32 | View::shouldReceive('exists')->once()->andReturn(true); |
||
| 33 | View::shouldReceive('make')->once()->with('hello', ['myData' => 'foo'], [])->andReturn(app('view')); |
||
| 34 | View::shouldReceive('render')->once()->andReturn('<br>'); |
||
| 35 | \App::shouldReceive('call')->once()->andReturn('foo'); |
||
| 36 | |||
| 37 | //act |
||
| 38 | $widget = new Widget3(); |
||
| 39 | render_widget($widget); |
||
| 40 | } |
||
| 41 | |||
| 42 | public function test_controller_method_is_called_on_some_other_class() |
||
| 43 | { |
||
| 44 | View::shouldReceive('exists')->once()->andReturn(true); |
||
| 45 | View::shouldReceive('make')->once()->with('hello', ['data' => 'aaabbb'], [])->andReturn(app('view')); |
||
| 46 | View::shouldReceive('render')->once()->andReturn('<br>'); |
||
| 47 | |||
| 48 | //act |
||
| 49 | $widget = new Widget4(); |
||
| 50 | render_widget($widget, ['arg1' => 'aaa', 'arg2' => 'bbb']); |
||
| 51 | } |
||
| 52 | |||
| 53 | public function test_data_is_passed_to_data_method_from_view() |
||
| 54 | { |
||
| 55 | View::shouldReceive('exists')->once()->andReturn(true); |
||
| 56 | View::shouldReceive('make')->once()->with('hello', ['data' => '222111'], [])->andReturn(app('view')); |
||
| 57 | View::shouldReceive('render')->once()->andReturn('<br>'); |
||
| 58 | //act |
||
| 59 | $widget = new Widget6(); |
||
| 60 | render_widget($widget, ['foo' => '111', 'bar' => '222']); |
||
| 61 | } |
||
| 62 | } |
||
| 63 |