[英]Factory bot and problems with loging in in RSpec
我在使用 Factory 機器人和以指定用戶身份登錄時遇到問題。 我正在嘗試在 rspec 中運行一個簡單的編輯測試。它是:
require "rails_helper"
RSpec.describe "Treat management", :type => :system do
before do
treat = FactoryBot.create(:treat)
user = build(:user, email: 'wojtek@gmail.com', password: 'password')
login_as(user)
driven_by(:selenium_chrome_headless)
end
it "enables me to edit treats" do
visit root_path
click_button 'Edit'
fill_in 'Name', with: 'A new name'
fill_in 'Content', with: 'A new content'
click_button "Update Treat"
expect(page).to have_text("Treat was edited successfully")
end
end
這是我的 Treat 工廠。 Treats 有一個名字,內容和一個給予者和一個接受者外鍵
FactoryBot.define do
factory :treat do
name {'my first factory treat'}
content {'this is my first treat created by a factory'}
giver factory: :user
receiver factory: :user
end
end
當然還有用戶工廠。 用戶由 email 和密碼定義
FactoryBot.define do
factory :user do
email {Faker::Internet.email}
password {'password'}
end
end
而且你必須知道編輯按鈕只有在登錄用戶也是提供者時才會出現。 我四處打聽,據說我的 Treat 工廠配置良好。 請幫我解決這個問題。 如果需要任何其他代碼部分,請在評論中告訴我,我會相應地進行更新。 當然,我知道有一種更簡單的方法來編寫此測試,但必須使用工廠。
1個
我已經嘗試在工廠中對用戶進行硬編碼(沒有 Faker gem),但這會觸發驗證錯誤 - email 已被占用。
現在FactoryBot.create(:treat)
將根據工廠定義為發送giver
創建User
,為receiver
創建User
。
FactoryBot.define do
factory :treat do
name {'my first factory treat'}
content {'this is my first treat created by a factory'}
giver factory: :user # tells the factory to create a User from the User Factory
receiver factory: :user # tells the factory to create a User from the User Factory
end
end
您在測試中調用它,然后創建第三個用戶進行測試
before do
treat = FactoryBot.create(:treat) # 2 users created
# changed to `create` since as @max pointed out `build` does not actually create a `User`
user = create(:user, email: 'wojtek@gmail.com', password: 'password') # third user
end
這第三個用戶既不是Treat
的giver
也不是receiver
,這就是您的測試失敗的原因。
相反,您可以通過傳遞 arguments 來創建來覆蓋Factory
中的定義。 在這種情況下,您希望被測試的User
giver
成為Treat
的提供者,因此我們可以按如下方式實現(我使用了@max測試方案的修改版本,因為這是設置它的首選方式)
require "rails_helper"
RSpec.describe "Treat management", type: :system do
let(:user) { create(:user) }
before do
driven_by(:selenium_chrome_headless)
end
context 'A Treat#giver' do
let!(:treat) {create(:treat, giver: user)}
before do
login_as(user)
end
it "can edit Treats they've given" do
visit root_path
click_button 'Edit'
fill_in 'Name', with: 'A new name'
fill_in 'Content', with: 'A new content'
click_button "Update Treat"
expect(page).to have_text("Treat was edited successfully")
end
end
end
在這里,我們用let
塊中定義的user
方法返回的特定用戶替換默認創建的“給予者”用戶。 這確保user == treat.giver
以便您的測試可以成功。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.