Rspec equal method

前端 未结 2 1370
自闭症患者
自闭症患者 2021-02-02 12:54

From what I have understood, the equal method checks if the object is the same.

person = Person.create!(:name => \"David\")
Person.find_by_name(\"David\").sho         


        
2条回答
  •  臣服心动
    2021-02-02 13:21

    Rails and RSpec equality tests have a variety of choices.

    Rails 3.2 ActiveRecord::Base uses the == equality matcher.

    It returns true two different ways:

    • If self is the same exact object as the comparison object
    • If self is the same type as the comparison object and has the same ID

    Note that ActiveRecord::Base has the == method which is aliased as eql?. This is different than typical Ruby objects, which define == and eql? differently.

    RSpec 2.0 has these equality matchers in rspec-expectations:

    a.should equal(b) # passes if a.equal?(b)
    a.should eql(b) # passes if a.eql?(b)
    a.should == b # passes if a == b
    

    RSpec also has two equality matchers intended to have more of a DSL feel to them:

    a.should be(b) # passes if a.equal?(b)
    a.should eq(b) # passes if a == b
    

    In your example you're creating a record then finding it.

    So you have two choices for testing #find_by_name:

    • To test if it retrieves the exact same object OR an equivalent Person record with the same ID, then use should == or its equivalent a.should eql or its DSL version should eq

    • To test if it uses the exact same object NOT an equivalent Person record with the same ID, then use should equal or its DSL version should be

提交回复
热议问题