我正在寫一個創建方法的成本,它會爲帖子添加評論。Rspec:在其他工廠中使用工廠
該評論屬於用戶和帖子。而帖子屬於用戶。
當我運行我的測試時,出現驗證錯誤,說明用戶名和電子郵件已被佔用。我試過在我的工廠和測試中都使用build和build_stubbed,但他們都沒有工作。我認爲這與我使用create相關,但我不完全確定。
任何建議,將不勝感激
這裏是我的工廠:
users.rb
FactoryGirl.define do
factory :user do
username "test_user"
email "[email protected]"
password "password"
end
factory :user_2, class: User do
username "test_user_2"
email "[email protected]"
password "password"
end
factory :invalid_user, class: User do
username ""
email ""
password ""
end
end
outlets.rb
FactoryGirl.define do
factory :outlet do
category "vent"
title "MyString"
body "MyText"
urgency 1
user factory: :user
end
factory :outlet_2, class: Outlet do
category "rant"
title "MyString_2"
body "MyText_2"
urgency 2
user factory: :user_2
end
factory :invalid_outlet, class: Outlet do
category "qualm"
title ""
body ""
urgency 3
user factory: :user
end
end
comments.rb
FactoryGirl.define do
factory :comment do
body "This is a comment"
user factory: :user
outlet factory: :outlet_2
end
factory :invalid_comment, class: Comment do
body "This is a comment"
user nil
outlet nil
end
end
這裏是我的測試:
describe 'create' do
context 'with valid attributes' do
let(:outlet) { FactoryGirl.create(:outlet) }
let(:valid_comment_params) { FactoryGirl.attributes_for(:comment) }
it "creates a new comment" do
expect { post :create, params: { id: outlet, :comment => valid_comment_params } }.to change(Comment, :count).by(1)
end
end
end
這裏是我的模型:
class Comment < ApplicationRecord
belongs_to :user
belongs_to :outlet
validates :body, :user, :outlet, presence: true
validates :body, length: { in: 1..1000 }
end
class Outlet < ApplicationRecord
belongs_to :user
has_many :comments
validates :category, :title, :body, :urgency, :user, presence: true
validates :title, length: { in: 1..60 }
validates :body, length: { in: 1..1000 }
validates :urgency, numericality: { only_integer: true, greater_than_or_equal_to: 1, less_than_or_equal_to: 10 }
validates :category, inclusion: { in: ['vent', 'rant', 'qualm'] }
end
class User < ApplicationRecord
has_many :outlets
has_many :comments
validates :username, :email, :encrypted_password, presence: true
validates :username, :email, uniqueness: true
validates :password, length: { in: 5..30 }
# Include default devise modules. Others available are:
# :lockable, :timeoutable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :omniauthable
end
您是否介意發佈您的型號代碼以及(特別是驗證)?這將有助於指導答案。 – Sean
好的,我剛剛使用型號代碼 –