pmichna
pmichna

Reputation: 4888

Can I test model instance attributes in a controller spec?

I have a controller spec:

let!(:user) { create(:user, balance: 1000) }
let!(:group) { create(:group) }
let!(:parenthood) { create :parenthood, user: user }

before :each do
  sign_in user
end

context 'when user wants to pay for own children' do
  let(:box) { build(:box, user: user, person_amount: 10, group: group) }
  it "decreases user's balance" do
    post :create, box: box.attributes.merge({'box_memberships_attributes'=>{'0'=>{'id'=>'', 'student_id'=>parenthood.student.id, '_destroy'=>'0'}},
                                             'pay_own_children' => 'true'})
    expect(user.balance).to eq(990)
  end
end

Pay no attention to the ugliness of that test. :)

This test returns an error:

Failure/Error: expect(user.balance).to eq(990)

       expected: 990
            got: 1000.0 (#<BigDecimal:c973608,'0.1E4',9(27)>)

       (compared using ==)

However, if I debug the tested method in the controller with binding.pry everything is OK:

def create
  # some code
  binding.pry
  # current_user.balance.to_s return "990"
end

Does it mean I can not test states of models in controller specs?

Upvotes: 0

Views: 44

Answers (1)

Marek Lipka
Marek Lipka

Reputation: 51151

Reload your user instance:

expect(user.reload.balance).to eq(990)

Upvotes: 2

Related Questions