我想在我的 rspec 控制器测试中测试员工是否与公司关联。
我想在我的create
工作人员财务主任的行动:
staff.companies << current_company
Where current_company
从会话变量中收集。
我该如何为此编写测试?
我有这些型号
class Company < ActiveRecord::Base
has_many :employees
has_many :staff, :through => :employees
end
class Employee < ActiveRecord::Base
belongs_to :company
belongs_to :staff
end
class Staff < ActiveRecord::Base
has_many :employees
has_many :companies, :through => :employees
end
以下测试是我尝试指定关联的尝试,当我输入关联代码时,它失败了:
it "should belong to the current_company" do
staff.should_receive(:companies)
post :create
end
如果我在控制器中输入“staff.companies
Failure/Error: post :create
NoMethodError:
You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.<<
员工控制器创建方法:
def create
@staff = Staff.new(params[:staff])
if @staff.save
@staff.companies << current_company
redirect_to staff_index_path, :notice => "Staff created successfully!"
else
@company = @staff.firm || current_company
flash[:alert] = "Staff failed to create"
render "new"
end
end