我在测试控制器的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控制台添加用户可以正常工作。任何帮助将受到高度赞赏。提前谢谢。
答案 0 :(得分:0)
这一行:
post :create, FactoryGirl.attributes_for(:admin_user)
应该是这样的:
post :create, :admin_user => FactoryGirl.attributes_for(:admin_user)
作为练习,请在控制器中的创建操作中打印参数(p params
或puts params.inspect
),然后您就会看到差异。
编辑你应该尝试两件事:
save
,请尝试使用save!
,如果您的任何验证错误,将会抛出错误,并且您会在测试输出中看到错误。如果保存失败,您应该处理这种情况。