2017-04-07 55 views
0

我對單元測試非常陌生,我試圖圍繞它進行測試。所以我有一個文章表單的情況下,用戶可以輸入titledescription並點擊Create Article文章應該創建,但只有登錄用戶可以執行此操作,所以我需要測試它。Ruby on Rails - 在測試用例中添加用戶

由於我是新來這個,所以這是我在想什麼,

  1. 如果用戶登錄我將創建第一個用戶
  2. 將其保存到會話這就是系統如何檢查(但後來我也認爲它不是一個瀏覽器,所以這種邏輯可能無法正常工作),那麼我如何提交表單作爲登錄用戶?

,這裏是我的嘗試

require 'rails_helper' 

    RSpec.feature 'adding article' do 
     scenario 'allow user to add an article' do 
     @user = User.create(:email => "[email protected]", :password => 'password', :username => 'saadia1') 
     session[:user_id] = @user.id 

     visit new_article_path 

     # @article = Article.user.to eql(@user = User.find_by(id: 6)) 
     fill_in "Title", with: "My Title" 
     fill_in "Description", with: "My description" 


     click_on("Create Article") 

     expect(page).to have_content("My Title") 
     expect(page).to have_content("My description") 

     end 
    end 

當我運行rspec spec/features/add_article_spec.rb

我看到

Failures:

1) adding article allow user to add an article Failure/Error: session[:user_id] = @user.id

NameError: 
    undefined local variable or method `session' for #<RSpec::ExampleGroups::AddingArticle:0x007f89285e32e8> 
# ./spec/features/add_article_spec.rb:6:in `block (2 levels) in <top (required)>' 

Finished in 0.0197 seconds (files took 1.35 seconds to load) 1 example, 1 failure

Failed examples:

rspec ./spec/features/add_article_spec.rb:4 # adding article allow user to add an article

所以我的問題是如何添加的物件,在記錄的命令用戶?我非常感謝這方面的幫助。

回答

0

您使用的設計進行驗證,如果是色器件提供了測試一些輔助函數也包括這條線在rail_helper.rb

config.include Devise::Test::ControllerHelpers, :type => :controller 這將幫助你用色器件sign_in helper方法,你西港島線不需要請參考link以獲取更多信息

+0

謝謝,是的,我正在使用設計。我會盡力回覆 – Saadia

0

這就是我最終創建測試用例的原因,因爲這是我的第一個測試用例之一,我不確定這是怎麼回事改進如此隨意查看

require 'rails_helper' 

RSpec.feature 'adding article' do  
    scenario 'allow user to add an article' do 
    user = FactoryGirl.create(:user) 
    visit login_path 
    fill_in 'Email', with: user.email 
    fill_in 'Password', with: user.password 
    click_button 'Log in' 
    expect(page).to have_content('You have successfully logged in') 


    visit new_article_path 

    fill_in "Title", with: "My Title" 
    fill_in "Description", with: "My description" 


    click_on("Create Article") 

    expect(page).to have_content("My Title") 
    expect(page).to have_content("My description") 

    end 
end 

這是我廠

# spec/factories/users 
FactoryGirl.define do 
    factory :user do 
    sequence(:username) { |n| "user#{n}" } 
    password 'password' 
    sequence :email do |n|n 
    "user_#{n}@example.com" 
    end 
    end 
end 

Finished in 0.4176 seconds (files took 2.54 seconds to load) 1 example, 0 failures

我還是想知道是否有可能在所有登錄在另一種情況下,用戶或所有這一切必須是一個方案的一部分。