保持rspec测试DRY

时间:2015-04-27 04:43:17

标签: rspec

我有以下rspec测试

 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

我的问题是用户登录后?第一个场景通过,但其余的都失败了。有没有办法确保其余的通过?我知道它失败了因为" end"在第一个场景之后。那么如何在一个页面中进行多个测试或在一个页面中进行嵌套测试?

任何帮助表示赞赏

1 个答案:

答案 0 :(得分:1)

请注意,scenarioitspecify是别名,因此他们会做同样的事情。

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