RSpec error: Mock "Employee_1" received an unexpected message: to_ary with (without arguments)

My application has two models: User and Employee, and their relationship is the user has_many.

As I try to write an Rspec test case for an 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 with this please? Thanks

+4
source share
3 answers

Rails can infer an identifier from an instance of the true model, how it works:

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

This does not work with mock_model for reasons that I don’t understand. You can simply pass the identifier explicitly:

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

I think the problem is that you are using mock_model, which will cause errors if you call a method on a model that you are not explicitly creating to wait. In this case, you can create your employee using stub_model, since you do not perform any call checks actually made for 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 
+6
source

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

 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 
+1
source

Source: https://habr.com/ru/post/1342676/


All Articles