Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble in mocking a database and stub :save

First of all I'm new in mock/stub, and I'm having trouble mocking/stubbing

This is my application code:

describe 'Register an User' do
    VALID_USERNAME = "..."
    VALID_PASSWORD =  "..."
    VALID_USER = User.new(VALID_USERNAME, VALID_PASSWORD)

    before (:each) do
        User.any_instance.stub(:save).and_return(true)
    end

    it 'should create a new user' do
        post :create, :username => VALID_USERNAME, :password => VALID_PASSWORD
        expect(response.status).to eq(201)
        #user_inserted = ...
        #expect(user_inserted).to eq(VALID_USER)
    end
end

And:

def create
        username = params[:username]
        password = params[:password]
        if not username or not password
            render :json => '', :status => 400
        else
            success = User.new(username, password).save
            if success
                render :json => '', :status => 201
            else
                render :json => '', :status => 500
            end
        end
    end

I'm trying to do a mock of ActiveRecord, to test 'create', without need to test 'get'. The idea here is when I call 'user.save' can save the user without use the database, and then I would access in my test case, so I garantee the user was 'inserted' on my database.

If I run my test, it pass, but I'm not verifying what I'm willing to do. Any help or idea?

Thanks!

like image 848
Felipe Docil Avatar asked Nov 11 '22 09:11

Felipe Docil


1 Answers

That doesn't make sense as you cannot test insertion in database without inserting in the database. Why?

Rails comes with build-in validations that become the first step on saving an item. If the validations pass, the item is inserted through ActiveRecord in the database. The database validations starts on this step, and if any fails, they raise an exception.

So. If you want to test if the user might be created in the database, add the validations to the model that matches to the database. And then you will be able to use the method is_valid?.

This will ensure that your user is valid to be stored in the database. And consequently, you will be able to use it anywhere knowing that: user_instance.is_valid? defines an insertable item.

I hope this is what you where asking.

like image 108
Jorge de los Santos Avatar answered Nov 14 '22 22:11

Jorge de los Santos