Reputation: 428
I'm testing 'get' method and getting error:
expected:
[{\"user_id\":11,\"user_first_name\":\"bob\",\"user_last_name\":\"marley\",\"user_picture\":\"/images/missing.png\",\"id\":2,\"text\":\"my third review\",\"date\":\"2013-12-27T09:08:06.364Z\"}]
got:
[{\"user_id\":11,\"user_first_name\":\"bob\",\"user_last_name\":\"marley\",\"user_picture\":\"/images/missing.png\",\"id\":2,\"text\":\"my third review\",\"date\":\"2013-12-27T09:08:06.000Z\"}]
what the hell? Why last numbers are different while all other fields are equal?
it "should return reviews for user" do
review = Review.create(reviewer_id: @user.id, user_id: @user2.id, text: 'my third review')
get 'get_reviews_for_user', user_id: @user2.id
expect(response).to be_success
json = JSON.parse(response.body)
expect(json['reviews'].to_json).to eq([{user_id: @user.id,
user_first_name: @user.first_name,
user_last_name: @user.last_name,
user_picture: @user.picture.url(:thumb),
id: review.id,
text: review.text,
date: review.created_at
}].to_json)
end
In controller:
def get_reviews_for_user
user = User.where(id: params[:user_id]).first
return render json: {success: false} if user.nil?
reviews = []
Review.where(user_id: user.id).each do |review|
reviewer = review.reviewer
reviews << {user_id: reviewer.id,
user_first_name: reviewer.first_name,
user_last_name: reviewer.last_name,
user_picture: reviewer.picture.url(:thumb),
id: review.id,
text: review.text,
date: review.created_at}
end
render json: { success: true, reviews: reviews }
end
Upvotes: 1
Views: 1295
Reputation: 7230
You can use Timecop to freeze the time to a give value like this : Timecop.freeze(Time.now)
.
You can also use a stub like this (in you test) :
allow(Review).to receive(:where).with(user_id: @user.id).and_return([review])
allow(review).to receive(:created_at).and_return(Time.now)
Upvotes: 3
Reputation: 29419
The times are different because the milliseconds are truncated when the time is translated into JSON.
Upvotes: 4