RSpec错误:模拟“Employee_1”收到意外消息:to_ary with(no args)

时间:2011-03-07 17:52:51

标签: ruby-on-rails rspec

我的应用程序有两个模型:用户和员工,他们的关系是用户has_many员工。

当我尝试为员工控制器编写Rspec测试用例时:

describe "GET 'edit'" do
  it "should get user/edit with log in" do
    log_in(@user)
    employee = mock_model(Employee, :id=>1, :user_id=>@user.id)
    get :edit, :id=>employee
    response.should be_success
  end
end

我的结果是:

....F

Failures:

  1) EmployeesController GET 'edit' should get user/edit with log in
     Failure/Error: get :edit, :id=>employee
       Mock "Employee_1" received unexpected message :to_ary with (no args)
     # C:in `find'
     # ./app/controllers/employees_controller.rb:41:in `edit'
     # ./spec/controllers/employees_controller_spec.rb:51:in `block (3 levels) in '

Finished in 4.31 seconds
5 examples, 1 failure

有人可以帮我解决这个问题吗?感谢

3 个答案:

答案 0 :(得分:6)

我认为问题是你正在使用mock_model,如果你在模型上调用一个你没有明确创建期望的方法,它会抛出错误。在这种情况下,您可以使用stub_model创建员工,因为您不对实际对模型进行的调用执行检查。

describe "GET 'edit'" do

  it "should get user/edit with log in" do
    log_in(@user)
    employee = stub_model(Employee, :id=>1, :user_id=>@user.id)
    get :edit, :id=>employee
    response.should be_success
  end
end

答案 1 :(得分:4)

Rails能够从真实的模型实例推断ID,这就是它的工作原理:

@employee = Employee.create
get :edit, :id => @employee

这不适用于mock_model,原因我不清楚。您只需明确传入ID:

  employee = mock_model(Employee, :id => 1, :user_id=>@user.id)
  get :edit, :id => employee.id # or just :id => 1

答案 2 :(得分:1)

我认为问题出在mock_model上,你可以使用double。

describe "GET 'edit'" do

  it "should get user/edit with log in" do
    log_in(@user)
    employee = double('employee', :id=>1, :user_id=>@user.id)
    get :edit, :id=>employee
    response.should be_success
  end
end