防止重复的代码

时间:2016-04-17 07:36:01

标签: ruby-on-rails ruby

我有这个测试:

    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

它有很多重复。我怎样才能缩短这个测试?

2 个答案:

答案 0 :(得分:1)

我会考虑添加辅助方法:

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

使用这种方法,您可以将测试更改为:

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

答案 1 :(得分:0)

[[:show], [:show, relative_path: "/Fun/Facts.html"]].each do
  |args|
  get(*args)
  assert Addressable::URI.parse(response.redirect_url).host == "vice.com"
end