【问题标题】:Rspec can't get controller create action to workRspec 无法让控制器创建操作起作用
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多