0

我在测试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 控制台添加用户就可以了。任何帮助将不胜感激。提前致谢。

4

1 回答 1

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!which 将引发错误,而不是 using ,您将在测试输出中看到错误。如果保存仍然失败,您应该处理这种情况。
于 2012-06-29T18:18:49.817 回答