Question

I am trying to test my codeigniter system using simpletest, however I keep getting the error. I am very new to PHP and codeigniter so please go easy.

   Fatal error: Call to a member function add() on a non-object in C:\xampp\htdocs\di2\application\tests\simple_test.php on line 35 

This is my test file, at the moment I am trying to simply add a new user to the database.

require_once BASEPATH."core/Model.php";
require_once APPPATH."models/Users_model.php";

class ExampleTest extends UnitTestCase
{

function ExampleTest()
{
    parent::__construct('Example tests');
}

///// All functions starting with "test" will be tested /////

function testSimpleStuff()
{
    $name = 'Andreas';
    $online = TRUE;

    $this->assertEqual($name, 'Andreas');
    $this->assertTrue($online);
}


//There are already 8 members in the table
function testAdd()
{
    $this->model->add("new member");
    $this->assertEqual($this->model->get(9),'new member');
    $this->assertNull($this->model->get(0));
    $this->assertNull($this->model->get(10));
}   

  }

This is the model I am calling:

class Users_model extends CI_Model 
{

    function __construct() 
    {        
        parent::__construct();
    }

    //Used to retrieve all of the members from the database and list them by their id in descending order
    function get($id = null) 
    {
        $this->db->select('id, first_name, last_name, dob, email_address, phone_number, address_line_1, address_line_2, town, county, postcode, student, volunteer');
        $this->db->from('Users');
        if (!is_null($id)) $this->db->where('id', $id);
        $this->db->order_by('id', 'desc');
        return $this->db->get()->result();
    }

    function add($data) 
    {
        $this->db->insert('Users', $data);
        return $this->db->insert_id();
    }

    function update($data, $id) 
    {
        $this->db->where('id', $id);
        $this->db->update('Users', $data);
        return $this->db->affected_rows();
    }

    function delete($id) 
    {
        $this->db->where('id', $id);
        $this->db->delete('Users');
        return $this->db->affected_rows();
    }

    function filterUsers()
    {
        return $this->db->get('Users')->result();
    }   

}

Can anyone please tell me why I am getting this error, and how I can go about fixing it. Cheers in advance.

Was it helpful?

Solution

This is not the right way to call a model in codeigniter.

$this->model->add("new member");

It should be-

$this->load->model('Users_model');
$this->Users_model->add('new member');

OTHER TIPS

This is because, in CodeIgntier, you need to include your model explicitly (we can also do it in autoload.php).

In your controller's constructor

function ExampleTest()
{
    parent::__construct('Example tests');
    $this->load->model('Users_model');
}

Now, call it from your controller like:

$this->Users_model->add("new member");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top