3

我想测试我的 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

factory.rb <-- 用 factorygirl 设置 tha 固定装置

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

我得到了错误

错误

任何想法?谢谢之前

4

1 回答 1

1

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

只需尝试在您的 FactoryGirl“设置”中切换两行,如下所示:

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

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

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

于 2013-01-22T17:29:21.157 回答