2014-02-11 15 views
4

我的問題是我必須爲每個水豚測試創建一個新用戶並登錄。在使用水豚的測試之間保持數據庫中的用戶?

下面是一個例子:

require 'spec_helper' 

describe "users" do 
    describe "user registration" do 
    it "should create a new user and log in" do 
     # Register a new user to be used during the testing process 
     visit signup_path 
     fill_in 'Email', with: 'testuser' 
     fill_in 'Password', with: 'testpass' 
     fill_in 'Password confirmation', with: 'testpass' 
     click_button 'Create User' 
     current_path.should == root_path 
     page.should have_content 'Thank you for signing up!' 
    end 
    end 

    describe "user login" do 
    it "should log in" do 

     # log in 
     visit login_path 
     fill_in 'Email', with: 'testuser' 
     fill_in 'Password', with: 'testpass' 
     click_button 'Log In' 
     current_path.should == root_path 
     page.should have_content 'Logged in!' 
    end 
    end 
end 

登錄測試失敗,因爲用戶不再在數據庫中爲測試是否存在。

這可以通過將兩者都放在一個測試中來解決,但我認爲這是不好的做法。

另外我還有另一個文件,目前正在使用before_do在每次測試之間註冊和登錄,這似乎也相當糟糕......你can see that code here

記錄這是我的第一個rails應用程序,所以也許我試圖做錯誤的方式。我想盡可能地把它弄乾。

水豚真的不好用在需要用戶登錄的頁面上嗎?

回答

1

我已經這樣做了。

require "spec_helper" 

    describe "Users" do 
    subject { page } 
    describe "User Registration" do 
     before { visit signup_path } 

     let(:submit) { "Sign up" } 

     describe "with invalid information" do 
      it "should not create a user" do 
      expect { click_button submit }.not_to change(User, :count) 
      end 
     end 

     describe "with valid information" do 
      before do 
      fill_in "Email",  with: "[email protected]" 
      fill_in "Password",  with: "foobar12" 
      fill_in "Password confirmation", with: "foobar12" 
      end 

      it "should create a user" do 
       expect { click_button submit }.to change(User, :count).by(1) 
      end 

      describe "after registration" do 
      before { click_button submit } 
      it { should have_content 'Thank you for signing up!' } 
      end 

      describe "after registration signout and login" do 
       let(:user) { User.find_by_email('[email protected]') } 
       before do 
       click_button submit 
       visit signout_path 
       sign_in user  # sign_in is a method which u can define in your spec/support/utilities.rb . Define once and use at multiple places. 
       end 
       it { should have_content 'Logged In!' } 
       it { should have_link('Logout') } 
      end 
     end 
    end  
    end 

#規格/支持/ utilities.rb

def sign_in(user) 
    visit sign_path 
    fill_in "Email", with: user.email 
    fill_in "Password", with: user.password 
    click_button "Log in" 
end 

你的每一個describeit塊將在父母的before塊,這就是爲什麼我們需要在上面的測試用例每塊click_button後運行。

+0

謝謝這是非常有用的:) –

相關問題