[英]RSpec scenario refactoring
有一些RSpec集成測試:
require 'spec_helper'
feature 'Authentication', js: true do
scenario 'Successfully Sign In' do
user = create(:user)
visit '/admin/signin'
expect(page).to have_content('Login to Admin Panel')
fill_in 'Email', with: user.email
fill_in 'Password', with: user.password
click_button 'Login'
expect(page).to have_content('Welcome to the administrative panel of "Hotels" service!')
end
scenario 'Failed Sign In' do
user = create(:user)
visit '/admin/signin'
expect(page).to have_content('Login to Admin Panel')
fill_in 'Email', with: user.email + '_wrong'
fill_in 'Password', with: user.password
click_button 'Login'
expect(page).to have_content('Invalid username/password')
end
scenario 'Repeated Sign In' do
user = create(:user)
visit '/admin/signin'
expect(page).to have_content('Login to Admin Panel')
fill_in 'Email', with: user.email
fill_in 'Password', with: user.password
click_button 'Login'
visit '/admin/signin'
expect(page).to have_content('Welcome to the administrative panel of "Hotels" service!')
end
scenario 'Sign Out' do
user = create(:user)
visit '/admin/signin'
expect(page).to have_content('Login to Admin Panel')
fill_in 'Email', with: user.email
fill_in 'Password', with: user.password
click_button 'Login'
click_link 'Sign out'
expect(page).to have_content('Login to Admin Panel')
end
end
如您所見,這些測試非常相似,我希望能夠重構它。 我聽說過shared_examples,但是我不了解場景中的這個概念。 請給我一些建議,以改善我的功能測試。 謝謝!
我會將這些重復的代碼放在這樣的/ spec / support /下的幫助文件中
module Features
module SessionHelpers
def sign_in(email, password)
visit '/admin/signin'
expect(page).to have_content('Login to Admin Panel')
fill_in 'Email', with: email
fill_in 'Password', with: password
click_button 'Login'
end
end
end
並在每種情況下都調用該方法
scenario 'Successfully Sign In' do
user = create(:user)
sign_in(user.email, user.password)
expect(page).to have_content('Welcome to the administrative panel of "Hotels" service!')
end
除了@Pavan答案之外,在這種情況下,您絕對應該before :each
使用,因此您的整個測試將是這樣的:
feature 'Authentication', js: true do
before :each do
user = create(:user)
sign_in(user.email, user.password)
end
scenario 'Successfully Sign In' do
expect(page).to have_content('Welcome to the administrative panel of "Hotels" service!')
end
scenario 'Repeated Sign In' do
visit '/admin/signin'
expect(page).to have_content('Welcome to the administrative panel of "Hotels" service!')
end
scenario 'Sign Out' do
click_link 'Sign out'
expect(page).to have_content('Login to Admin Panel')
end
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.