【发布时间】:2017-07-07 16:41:13
【问题描述】:
整天都在努力编写正确的测试,但我想不通。
评论属于用户和出口 每个出口都有一个用户 每个out都有很多cmets 每个用户都有很多网点
目前我收到此错误:
Failure/Error: let(:outlet) { FactoryGirl.build(:outlet) }
ActiveRecord::RecordInvalid:
Validation failed: Username has already been taken, Email has already been taken
我真的不知道还能尝试什么。我已经尝试过切换我的工厂和测试,但只有不同的错误。任何帮助将不胜感激
工厂:
FactoryGirl.define do
factory :comment do
body "This is a comment"
user
outlet
end
factory :invalid_comment, class: Comment do
body "This is a comment"
user nil
outlet nil
end
end
FactoryGirl.define do
factory :outlet do
category "vent"
title "MyString"
body "MyText"
urgency 1
user
end
factory :invalid_outlet, class: Outlet do
category "qualm"
title ""
body ""
urgency 3
user factory: :user
end
end
FactoryGirl.define do
factory :user do
sequence(:username) { |n| "test_user#{n}" }
sequence(:email) { |n| "test_user#{n}@email.com" }
password "password"
end
factory :invalid_user, class: User do
username ""
email ""
password ""
end
end
测试
describe 'create' do
context 'with valid attributes' do
let(:outlet) { FactoryGirl.create(:outlet) }
let(:comment_params) { FactoryGirl.attributes_for(:comment) }
let(:create) { post :create, params: { id: outlet , comment: comment_params } }
it "creates new comment" do
puts outlet
puts comment_params
expect { create }.to change { Comment.count }.by 1
end
end
end
class CommentsController < ApplicationController
def new
@comment = Comment.new
end
def create
@outlet = Outlet.find(params[:id])
@comment = @outlet.comments.build(comment_params)
if @comment.save
redirect_to(@outlet)
end
end
private
def comment_params
params.require(:comment).permit(:body, :outlet_id, :user_id)
end
end
【问题讨论】:
-
您是说该错误是由
FactoryGirl.build(:outlet)引起的,但它并未出现在您的代码中的任何位置。这都是最新的吗?
标签: ruby-on-rails ruby rspec tdd