2015-04-27 41 views
1

我有以下RSpec的测试保持RSpec的测试DRY

feature "#Create New User" do 

    scenario "Sign In" do 
    sign_in 
    end 

    scenario "direct to create new user page" do 
    click_link 'Admin' 
    click_link 'User Maintenance' 
    click_link 'Create' 
    end 

    it "user name must not be blank" do 
    fill_in "user_name", :with => "" 
    select2("Loanstreet", "UserType") 
    expect(page).to have_content "Name can't be blank" 


    it "user name length must longer than 5" do 
    fill_in "user_name", :with => "Euge" 
    select2("Loanstreet", "UserType") 
    expect(page).to have_content "Name length must be longer than 5" 

    end 
end 

我的问题是,用户登录后?第一个场景过去了,但其余的都失败了。有没有一种方法可以确保其他人也能通过?我知道它在第一种情景之后因“结束”而失败。那么我如何在一个页面中执行多个测试或者在一个页面中进行嵌套测试呢?

任何帮助表示赞赏

回答

1

注意scenarioit,并且specify是别名,所以他们做同样的事情。

feature "#Create New User" do 

    # These two scenarios should not be like that, these are just 
    # preparations required by the other scenarios to pass 
    # scenario "Sign In" do 
    # sign_in 
    # end 

    # scenario "direct to create new user page" do 
    # click_link 'Admin' 
    # click_link 'User Maintenance' 
    # click_link 'Create' 
    # end 

    # they should be used in a before hook, which will be run before 
    # each scenario 
    before do 
    sign_in   
    click_link 'Admin' 
    click_link 'User Maintenance' 
    click_link 'Create' 
    end 

    # or you can make it a before :all so that it runs only once 
    # before all the scenarios 
    # before :all do 
    # sign_in   
    # click_link 'Admin' 
    # click_link 'User Maintenance' 
    # click_link 'Create' 
    # end 

    # it "user name must not be blank" do 
    scenario "changes user name with a blank string" do 
    fill_in "user_name", :with => "" 
    select2("Loanstreet", "UserType") 
    expect(page).to have_content "Name can't be blank" 
    end 

    # it "user name length must longer than 5" do 
    scenario "changes user name with a string shorter than 5" do 
    fill_in "user_name", :with => "Euge" 
    select2("Loanstreet", "UserType") 
    expect(page).to have_content "Name length must be longer than 5" 
    end 
end 
+0

因此,每次我必须在每种情况下执行上述操作。有没有其他的方式只做一次,并调用多个测试。或者是rspec允许它的唯一方法?感觉每次登录似乎都有很多功能重复。但是,感谢您的答案@nafaa –

+0

您可以在'spec_helper'或'rails_helper'文件中执行此操作,'Rspec.before do sign_in end',但这不是此功能的用途。如果你想要,你可以定义一个函数来完成登录,并在你需要时调用它。这是进行示例设置和准备的正确方法,我想它们不是其他方式。 –