2016-01-21 131 views
0

我需要測試一個只有在用戶使用Devise登錄後才能使用的系統。每次使用「它」時,我都必須包含註冊碼。如何計算Capybara rspec測試代碼?

有沒有辦法將以下代碼考慮進去,以便"let's me make a new post"測試和類似測試不必包含註冊?

describe "new post process" do 
    before :all do 
    @user = FactoryGirl.create(:user) 
    @post = FactoryGirl.create(:post) 
    end 

    it "signs me in" do 
    visit '/users/sign_in' 
    within(".new_user") do 
     fill_in 'Email', :with => '[email protected]' 
     fill_in 'Password', :with => 'password' 
    end 
    click_button 'Log in' 
    expect(page).to have_content 'Signed in successfully' 
    end 

    it "let's me make a new post" do 
    visit '/users/sign_in' 
    within(".new_user") do 
     fill_in 'Email', :with => '[email protected]' 
     fill_in 'Password', :with => 'password' 
    end 
    click_button 'Log in' 

    visit '/posts/new' 
    expect(find(:css, 'select#post_id').value).to eq('1') 
    end 

end 
+0

https://github.com/plataformatec/devise/wiki/How-To:-Test-with-Capybara – Jon

+0

你想「讓我做一個新的職位」測試不運行註冊,對吧? – fabersky

+0

@fabersky我希望它記住之前註冊過的用戶,這樣我就不必在每次測試時都包含該代碼 – Tom

回答

0

你的第一選擇是使用所提供的Warden方法,按照文件在此頁上:

https://github.com/plataformatec/devise/wiki/How-To:-Test-with-Capybara

你的第二個選擇是剛登錄真正在你的測試,你有在你的例子中完成。通過創建一些輔助方法來完成登錄工作,而不是在所有測試中重複代碼,您可以簡化此操作。

爲此,我將在您的spec目錄中創建一個support目錄,然後在該目錄中創建一個macros目錄。然後創建一個文件spec/support/macros/authentication_macros.rb

module AuthenticationMacros 
    def login_as(user) 
    visit '/users/sign_in' 
    within('.new_user') do 
     fill_in 'Email', with: user.email 
     fill_in 'Password', with: user.password 
    end 
    click_button 'Log in' 
    end 
end 

接下來,更新您的RSpec config來加載宏。在這兩種spec_helper.rbrails_helper.rb如果您使用的是較新的設置:

# Load your support files 
Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f } 

# Include the functions defined in your modules so RSpec can access them 
RSpec.configure do |config| 
    config.include(AuthenticationMacros) 
end 

最後,更新你的測試使用您的login_as功能:

describe "new post process" do 
    before :each do 
    @user = FactoryGirl.create(:user) 
    @post = FactoryGirl.create(:post) 

    login_as @user 
    end 

    it "signs me in" do 
    expect(page).to have_content 'Signed in successfully' 
    end 

    it "let's me make a new post" do 
    expect(find(:css, 'select#post_id').value).to eq('1') 
    end 
end 

顯然,要確保你有password在用戶定義的廠。

相關問題