Rspec无法让控制器创建动作

时间:2017-02-18 01:27:13

标签: ruby-on-rails ruby rspec tdd

一直在努力写出正确的测试,但我无法弄清楚。

评论属于用户和插座 每个插座都有一个用户 每个人都有很多评论 每个用户都有很多网点

目前我收到此错误:

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

1 个答案:

答案 0 :(得分:0)

错误表明您生成的用户名/电子邮件与数据库中的名称冲突。如果您在以后的运行中仍然在数据库中创建了一次运行的用户名,则可能会发生这种情况。

如果您还没有使用它,请考虑将DatabaseCleaner gem添加到您的项目中。它提供了各种方法来确保在运行之间重置数据库。