I have seen this kind of notation elsewhere: @user = FactoryGirl.create(:user)
, but can't figure out exactly how this instance variable will behave.
Specifically, I'm wondering about the behavior of this instance variable. For example, I'm currently creating integration tests in RSpec. In one of the tests, I tried to assign an instance variable to an instance of my Video class:
@video = FactoryGirl.create(:video, title: "Test title")
I have no trouble at that point accessing the different attributes of the video instance (e.g., using @video.title
)).
However, I am creating an integration test to make sure that a user can clear the "title" field in the form and when the video updates, the title is erased in the database. E.g.,
click_link "Edit"
fill_in "Title", with: ""
click_button "Update Video"
expect(find('#title')).to_not have_content "Test title"
For some reason, the page displays correctly, but when I try to access the instance using the instance variable, no change has occurred: print @video.title
returns "Test title"
What is strange is that in a different integration test I use a similar process to update the video instance's attributes (e.g., to "Updated Test title"). I then tested to see if the attributes updated correctly in the webpage, and they did, but this time instance variable also reflected that (using print @video.title
).
Any guesses on why this would be the case?
The solution is to use @video.reload.title
, to update record from DB.
When you create @video
it is now disconnected from the database changes (static copy in a Video object) reload
will cause it to refresh itself from the database showing the changes made since its initial assignment.
Resources include:
(Credit goes to @SergiiK and @engineersmnky who answered the question in the above comments.)