2014-05-11 95 views
0

這是我的天賦的幫手之一:如何通過功能參數

def remove_slides_from_page(to_delete_array, to_leave_array, button_name) 
    to_delete_array.map { |slide| 
    page.check("slide_select_#{slide.id}") 
    } 

    click_button(button_name) # <- I would like to pass this command(s) as an argument 

    to_leave_array.map { |slide| 
    expect(page).to have_selector("tr#slide_#{slide.id}") 
    expect(page).to have_field("slide_select_#{slide.id}") 
    expect(page).to have_field("slide_delete_#{slide.id}", visible: false) 
    expect(page).to have_field("slide_move_#{slide.id}", visible: false) 
    } 
    to_delete_array.map {|slide| 
    expect(page).to_not have_selector("tr#slide_#{slide.id}") 
    expect(page).to_not have_field("slide_select_#{slide.id}") 
    expect(page).to_not have_field("slide_delete_#{slide.id}") 
    expect(page).to_not have_field("slide_move_#{slide.id}") 
    }   
end 

與其說這remove_slides_from_page(@foo, @bar, "baz")我希望能夠通過click_button("baz")作爲其最後一個參數(拉姆達?)不知何故。我想問你的幫助,因爲我不知道如何在Ruby中製作它。

+0

的http://stackoverflow.com/questions/522720/passing-a-method-as-a-parameter-in-ruby – armadadrive

回答

2

使用yield

def remove_slides_from_page(to_delete_array, to_leave_array) 
    to_delete_array.map { |slide| 
    page.check("slide_select_#{slide.id}") 
    } 

    yield 

    to_leave_array.map { |slide| 
    expect(page).to have_selector("tr#slide_#{slide.id}") 
    expect(page).to have_field("slide_select_#{slide.id}") 
    expect(page).to have_field("slide_delete_#{slide.id}", visible: false) 
    expect(page).to have_field("slide_move_#{slide.id}", visible: false) 
    } 
    to_delete_array.map {|slide| 
    expect(page).to_not have_selector("tr#slide_#{slide.id}") 
    expect(page).to_not have_field("slide_select_#{slide.id}") 
    expect(page).to_not have_field("slide_delete_#{slide.id}") 
    expect(page).to_not have_field("slide_move_#{slide.id}") 
    }   
end 

remove_slides_from_page(to_delete_array, to_leace_array) { click_button('baz') } 
+0

可能的複製,我覺得'yield'到非常容易混淆......特別是如何調用帶有yield的函數。 – pawel7318

+1

請參閱本教程:http://www.tutorialspoint.com/ruby/ruby_blocks.htm –