4
votes

My application has two models: User and Employee, and their relation is user has_many employees.

As I trying to write a Rspec test case for the employee controller:

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

I got the result as:

....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

Can someone help me out with this please? Thanks

3

3 Answers

7
votes

I think the problem is you are using mock_model, which will throw errors if you call a method on the model that you are not explicitly creating an expectation for. In this case, you could create you employee with stub_model since you are performing no checks on calls actually made to the 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
4
votes

Rails is able to infer the ID from a true model instance, which is how this works:

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

This doesn't work with mock_model, for reasons that are unclear to me. You can simply pass in the ID explicitly:

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

I think the problem is with mock_model, you can use double for that.

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