John Smith John Smith - 7 months ago 28
Ruby Question

Prevent duplicated code

I have this test:

it "redirects him to vice" do
get :show
uri_request_1 = Addressable::URI.parse(response.redirect_url)
redirects_to_vice_1 = uri_request_1.host == "vice.com"

get :show, relative_path: "/Fun/Facts.html"
uri_request_2 = Addressable::URI.parse(response.redirect_url)
redirects_to_vice_2 = uri_request_1.host == "vice.com"

assert redirects_to_vice_1 && redirects_to_vice_2
end


It has a lot of repetition. How can I shorten this test?

Answer

I would think about adding a helper method:

def assert_redirection_to(host)
  assert Addressable::URI.parse(response.redirect_url) == host
end

With such a method you could change your tests to:

describe 'without parameters' do 
  it 'redirects to vice.com' do
    get :show
    assert_redirection_to 'vice.com'
  end
end

describe 'with parameters' do 
  it 'redirects to vice.com'
    get :show, relative_path: '/Fun/Facts.html'
    assert_redirection_to 'vice.com'
  end
end