So here's the method I want to test:
def self.by_letter(letter)
where("lastname LIKE ?", "#{letter}%").order(:lastname)
end
Quick question here, what exactly does the percent sign after #{letter} do? Something to do with formatting?
Here's part of the spec that tests that method:
context 'method "by_letter"' do
it 'returns and ordered list by letter' do
theon = Contact.create!(
firstname: "Theon",
lastname: "Greyjoy",
email: "[email protected]"
)
rob = Contact.create!(
firstname: "Rob",
lastname: "Stark",
email: "[email protected]"
)
tyrion = Contact.create!(
firstname: "Tyrion",
lastname: "Lannister",
email: "[email protected]"
)
result = Contact.by_letter("S")
expect(result).to include("Snow")
end
end
And here's the logs I get for an output after running said test (oh, bare in mind, earlier in the spec I created a "Jon Snow", and he should pop up before "Stark" alphabetically):
Failures:
1) Contact method "by_letter" returns and ordered list by letter
Failure/Error: expect(result).to include("Snow")
expected #<ActiveRecord::Relation [#<Contact id: 1, firstname: "Jon", lastname: "Snow", email: "[email protected]", created_at: "2014-11-14 17:17:55", updated_at: "2014-11-14 17:17:55">, #<Contact id: 3, firstname: "Rob", lastname: "Stark", email: "[email protected]", created_at: "2014-11-14 17:17:56", updated_at: "2014-11-14 17:17:56">]> to include "Snow"
Diff:
@@ -1,2 +1,3 @@
-["Snow"]
+[#<Contact id: 1, firstname: "Jon", lastname: "Snow", email: "[email protected]", created_at: "2014-11-14 17:17:55", updated_at: "2014-11-14 17:17:55">,
+ #<Contact id: 3, firstname: "Rob", lastname: "Stark", email: "[email protected]", created_at: "2014-11-14 17:17:56", updated_at: "2014-11-14 17:17:56">]
What am I missing? Shouldn't my test pass because I return a collection that includes a string I specified? Is there some complication because it's not a regular array but some sort of proxy array? What do I need to do to get my test to pass?
Your result
is an ActiveRecord::Relation
object. So you should do as below :-
expect(result).to include(rob)
rob
has the last name as "Stark"
, thus Contact.by_letter("S")
will include rob
in the filtered list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With