我對單元測試非常陌生,我試圖圍繞它進行測試。所以我有一個文章表單的情況下,用戶可以輸入title
和description
並點擊Create Article
文章應該創建,但只有登錄用戶可以執行此操作,所以我需要測試它。Ruby on Rails - 在測試用例中添加用戶
由於我是新來這個,所以這是我在想什麼,
- 如果用戶登錄我將創建第一個用戶
- 將其保存到會話這就是系統如何檢查(但後來我也認爲它不是一個瀏覽器,所以這種邏輯可能無法正常工作),那麼我如何提交表單作爲登錄用戶?
,這裏是我的嘗試
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
所以我的問題是如何添加的物件,在記錄的命令用戶?我非常感謝這方面的幫助。
謝謝,是的,我正在使用設計。我會盡力回覆 – Saadia