2013-12-15 90 views
0

說,我有一個這樣的試驗:Rspec的:定義測試組的方法,它的參數

describe "signin" do 
    before { visit root_path } 

    describe "with invalid data" do 
     before { click_button "Sign in" } 

     it { should have_error_message("Invalid") } 
     it { should_not have_link("Sign out") } 
     it "should redirect to same page" do 
     current_path.should == root_path 
     end 
    end 

    end 

而且我想在任何要進行相同的測試另一頁太(不root_path):它應該被重定向到同一頁面。

所以,我想保持乾燥,因此要在一個位置聲明此測試,並用不同的參數調用它:首先使用root_path,然後再使用其他頁面。

我知道我們可以在support/utilities.rb中定義自定義匹配器,但是我們如何定義測試呢?

回答

1

如果我正確理解你的問題,你要執行,但具有不同的目前是什麼root_path值相同的代碼(即您將參觀一些其他的路徑,並重定向到其他路徑的情況下,輸入無效數據)。

在這種情況下,你要provide context to a shared example

shared_examples_for "visit and click sign in" do 
    before do 
    visit path 
    click_button "Sign in" 
    end 
    it { should have_error_message("Invalid") } 
    it { should_not have_link("Sign out") } 
    it "should redirect to same page" do 
    current_path.should == path 
    end 
end 

describe "root signin" do 
    it_behaves_like "visit and click sign in" do 
    let(:path) {root_path} 
    end 
end 

你不能僅僅通過在root_path因爲參數shared_examples在RSpec的背景下得到評估,而不是「測試環境」。

+0

謝謝,這正是我需要的。 –

1

我會用一個Shared example group。例如。

shared_examples_for "redirect and show error" do 
    it { should have_error_message("Invalid") } 
    it { should_not have_link("Sign out") } 
    it "should redirect to same page" do 
    current_path.should == root_path 
    end 
end 

describe "signin" do 
    before { visit root_path } 

    describe "with invalid data" do 
    before { click_button "Sign in" } 
    it_behaves_like "redirect and show error" 
    end 
end