post:在rspec测试中创建,给'计数应该已经改变1,但被改为0'

时间:2012-06-29 18:09:13

标签: ruby-on-rails rspec2 ruby-on-rails-3.2 factory-bot rspec-rails

我在测试控制器的create方法时遇到了问题。我的测试:

describe "POST #create" do
  it "creates a new admin_user" do
    expect{
      post :create, :admin_user => FactoryGirl.attributes_for(:admin_user)
    }.to change(Admin::User,:count).by(1)
  end
end

我得到的失败规范:

1) Admin::UsersController logged in POST #create creates a new admin_user
     Failure/Error: expect{
       count should have been changed by 1, but was changed by 0
     # ./spec/controllers/admin_users_controller_spec.rb:75:in `block (4 levels) in <top (required)>'

这是我的控制器:

  def create
    @admin_user = Admin::User.new(params[:admin_user])
    if @admin_user.save
      render nothing: true
    end
  end

和工厂:

require "factory_girl"
require 'ffaker'

FactoryGirl.define do
  factory :admin_user, class: "Admin::User" do |f|
    f.name {Faker::Name.first_name}
    f.email {Faker::Internet.email}
    f.password "aaa"
  end
end

和我的模特:

class Admin::User < ActiveRecord::Base
  has_secure_password
  validates :email, :uniqueness => true, :presence => true 
  validates_presence_of :password, :on => :create
end

我不知道可能出现什么问题。我已经搜索了整个互联网,但没有找到答案。从rails控制台添加用户可以正常工作。任何帮助将受到高度赞赏。提前谢谢。

1 个答案:

答案 0 :(得分:0)

这一行:

post :create, FactoryGirl.attributes_for(:admin_user)

应该是这样的:

post :create, :admin_user => FactoryGirl.attributes_for(:admin_user)

作为练习,请在控制器中的创建操作中打印参数(p paramsputs params.inspect),然后您就会看到差异。

编辑你应该尝试两件事:

  1. 仍打印出参数,看看它们是否对你有意义。
  2. 问题可能是你的参数无效。不要使用save,请尝试使用save!,如果您的任何验证错误,将会抛出错误,并且您会在测试输出中看到错误。如果保存失败,您应该处理这种情况。