2013-12-15 45 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