得到错误:不能为空,Rails测试

时间:2012-06-07 03:02:46

标签: ruby-on-rails-3 factory-bot functional-testing

我想测试我的rails应用程序,特别是在控制器上,这里是代码

customer_controller_test.rb

    require 'test_helper'

class CustomersControllerTest < ActionController::TestCase
  include Devise::TestHelpers

  setup do
    @user = FactoryGirl.create(:user)    
    @role = FactoryGirl.create(:role)
    #puts @role.name
    @permission = FactoryGirl.create(:permission)
    #puts @permission.name
    @role_permission = FactoryGirl.create(:role_permission)
    #puts @role_permission.role_id
    #puts @role_permission.permission_id
    sign_in @user
    @customer = FactoryGirl.create(:customer)
  end

  test "should get index" do
    get :index
    assert_response :success
    assert_template 'index'
    assert_not_nil assigns(:customers)
  end

  test "should show article" do
    get :show, :id => @customer.to_param

    assert_response :success
    assert_template 'show'

    assert_not_nil assigns(:customer)
    assert assigns(:customer).valid?
  end

  test "should get new" do
    #login_as(@user)
    get :new
    assert_response :success
  end
end

factories.rb&lt; - 与factorygirl建立装置

FactoryGirl.define do

  sequence :email do |n| "admin@admin.admin#{n}" end
  sequence :role_name do |n| n end
  sequence :role_id do |n| n end
  sequence :permission_id do |n| n end

factory :user do |u|
    u.name           "Admin"
    u.role_id        {1}
    u.email          do FactoryGirl.generate(:email) end
    u.password       "123456"
    u.after(:create) do |user|
        user.creator_id  {1} 
        user.save
    end
  end

factory :customer do
    name    "Test customer-name"
    code    "Test customer-code"
    address "Test customer-address"
    phone   "Test customer phone"
  end

factory :permission do
    name "Customer"
  end

  factory :role do
    name do FactoryGirl.generate(:role_name) end
  end
end

我收到了错误

error

有什么想法吗?在此之前

1 个答案:

答案 0 :(得分:1)

尝试在将其分配给用户之前在FactoryGirl中创建角色。保存用户记录时,您似乎遇到验证错误,因为它正在尝试验证您是否已分配实际角色。你不这样做,因为你试图在用户之后创建你的角色。

只需尝试在FactoryGirl“设置”中切换两行:

@role = FactoryGirl.create(:role)
@user = FactoryGirl.create(:user)    

或者,请查看此链接以更全面地了解如何使用FactoryGirl测试关联:

http://blog.joshsoftware.com/2011/05/13/testing-associations-with-factory-girl/