post创建测试用户计数失败。应更改为1,但更改为0

时间:2013-07-30 23:49:25

标签: ruby-on-rails post rspec controller

现在试图弄清楚这一段时间,但似乎无法变绿。这是我得到的rspec错误:

 1) UsersController POST create with valid parameters creates a new user
     Failure/Error: expect {post :create, user}.to change(User, :count).by 1
       count should have been changed by 1, but was changed by 0
     # ./spec/controllers/users_controllers_spec.rb:36:in `block (4 levels) in <top     
(required)>'

以下是我在users_controllers_spec中的相关测试:

describe UsersController do
  let(:user) {FactoryGirl.create :user}

  context 'POST create' do 

   context 'with valid parameters' do 
    before {post :create, user}
    let(:user) {FactoryGirl.build :user}


    it 'creates a new user' do 
     expect {post :create, user}.to change(User, :count).by 1
    end


   it {should respond_with 200}
 end

这是我的users_controller创建方法:

def create
   @user = User.new(params[:user])
    if @user.save
     sign_in @user
     flash[:success] = "Welcome #{@user.name.capitalize}! Please complete your profile."
     redirect_to profile_path(current_user)
   else
    render :new
  end
end

另外,这是我的factories.rb文件:

FactoryGirl.define do 
  factory :user do 
    name  "John"
    email "John@example.com"
    password  "password"
    password_confirmation "password"
  end
end

我错过了什么?我觉得这是非常明显的事情,但我似乎无法弄明白。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

您的测试涉及使用FactoryGirl创建第二个用户,但第二个用户的创建失败,因为该电子邮件与第一个用户相同,并且您对该属性进行了唯一性验证。

您可以根本不创建第一个用户,或者您需要使电子邮件不同(例如,通过将电子邮件参数传递到您的FactoryGirl电话或更改工厂以使每个电子邮件地址唯一)