RSpec 'Expect' Syntax and Idiomatic attribute spec

前端 未结 2 2025
名媛妹妹
名媛妹妹 2021-02-13 22:13

This should have an easy answer but I\'m struggling to find it (have checked RSpec documentation, EverydayRails Testing with RSpec, Google results). In my model specs I like to

相关标签:
2条回答
  • 2021-02-13 22:57

    Myron Marston, one of the core RSpec committers, explains here that you should still use

    it { should be_cool }
    

    If you've disabled the should syntax, he offers a solution to alias expect_it to it:

    RSpec.configure do |c|
      c.alias_example_to :expect_it
    end
    
    RSpec::Core::MemoizedHelpers.module_eval do
      alias to should
      alias to_not should_not
    end
    

    With this in place, you could write this as:

    describe User do
      expect_it { to be_valid }
    end
    
    0 讨论(0)
  • 2021-02-13 23:05

    I don't think there's a correct answer to this question, but I've been recently rewriting my test suites to move away from should and use the expect syntax exclusively, so I'll throw my two cents in. I decided to re-write pretty much because Myron Marston, the RSpec lead maintainer, wrote:

    In the future, we plan to change the defaults so that only expect is available unless you explicitly enable should. We may do this as soon as RSpec 3.0, but we want to give users plenty of time to get acquianted with it.

    He also commented:

    We have no plans to ever remove "should"...but expect has fewer gotchas, and is the syntax I would recommend for new projects.

    I do agree with Mark Rushakoff's answer as well, but personally I don't want to have to create those aliases just to keep a single it-block style syntax. So, using your example, where originally I wrote a model spec like your example in this form:

    describe Foo do
      let(:foo) { create(:foo) }
      subject { foo }
      describe "model attributes" do
        it { should be_valid }
        it { should respond_to(:color) }
        it { should respond_to(:height) }
        it { should respond_to(:some_other_attribute) }
        it { should respond_to(:you_get_the_idea) }
      end
      # ...
    end
    

    I now would tend to write it like:

    describe Foo do
      let(:foo) { create(:foo) }
      specify "model attributes" do
        expect(foo).to be_valid
        expect(foo).to respond_to(:color)
        expect(foo).to respond_to(:height)
        expect(foo).to respond_to(:some_other_attribute)
        expect(foo).to respond_to(:you_get_the_idea)
      end
      # ...
    end
    

    My opinion is that referencing foo directly in expect(foo).to respond_to(:color) is as much "duplication" as referencing a subject indirectly using it, so I'm not too phased about it, and I'm warming to the way that expect specs generally read. But, ultimately I think this comes down to just being an issue of preferred writing style.

    0 讨论(0)
提交回复
热议问题