RSpec Matchers When Working With ActiveRecord::Relation

泪湿孤枕 提交于 2019-12-10 17:33:58

问题


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: "tgreyjoy@ironprice.com"
        )
      rob = Contact.create!(
       firstname: "Rob", 
       lastname: "Stark", 
       email: "rstark@winterfell.com" 
       )
      tyrion = Contact.create!(
       firstname: "Tyrion", 
       lastname: "Lannister", 
       email: "tlannister@kingslanding.com" 
       )
      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: "lordcommander@nightswatch.com", created_at: "2014-11-14 17:17:55", updated_at: "2014-11-14 17:17:55">, #<Contact id: 3, firstname: "Rob", lastname: "Stark", email: "rstark@winterfell.com", 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: "lordcommander@nightswatch.com", created_at: "2014-11-14 17:17:55", updated_at: "2014-11-14 17:17:55">,
       + #<Contact id: 3, firstname: "Rob", lastname: "Stark", email: "rstark@winterfell.com", 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?


回答1:


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.




回答2:


Try expect(result.first).to include("Snow")

You can also say (preferably):

expect(result.first.lastname).to eq("Snow")



来源:https://stackoverflow.com/questions/26935630/rspec-matchers-when-working-with-activerecordrelation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!