【问题标题】:How Can I Refactor These Assertions To Avoid Duplication我如何重构这些断言以避免重复
【发布时间】:2014-01-27 13:19:14
【问题描述】:

有没有办法重构它以避免重复:

post :create, user: attributes_for(:user)

鉴于第一个断言需要将其包装在 expect 块中,我看不到将其移动到 before 块的方法。显然,我可以将最后两个断言包装在 contextdescribe 块中,并带有自己的 before 块,但这感觉不对。

   context 'with valid attributes' do

    it 'should create a new User and save it to the database' do
      expect {
        post :create, user: attributes_for(:user)
      }.to change(User, :count).by(1)
    end

    it {
      post :create, user: attributes_for(:user)
      should redirect_to(user_path(assigns[:user]))
    }

    it {
      post :create, user: attributes_for(:user)
      should set_the_flash[:notice]
    }

  end

【问题讨论】:

    标签: ruby-on-rails rspec ruby-on-rails-4 refactoring shoulda


    【解决方案1】:

    你可以把你的“动作”放在一个方法中,如下:

    context 'with valid attributes' do
      it 'should create a new User and save it to the database' do
        expect {
          do_action
        }.to change(User, :count).by(1)
      end
    
      it {
        do_action
        should redirect_to(user_path(assigns[:user]))
      }
    
      it {
        do_action
        should set_the_flash[:notice]
      }
    
      def do_action
        post :create, user: attributes_for(:user)
      end
    end
    

    【讨论】:

      【解决方案2】:

      类似这样的东西(不确定它是否有效)

        context 'with valid attributes' do
          before { post :create, user: attributes_for(:user) }
      
          it 'should create a new User and save it to the database' do
            expect(User.count).to eq 1
          end
      
          it { should redirect_to(user_path(assigns[:user])) }
          it { should set_the_flash[:notice] }
        end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-17
        • 1970-01-01
        • 2017-06-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多