【问题标题】:RSpec Helper Parameters IssueRSpec 助手参数问题
【发布时间】:2015-07-23 15:16:22
【问题描述】:

我正在尝试测试以下代码:

module ApplicationHelper
  def current_book
    Book.find(params[:id])
  end
end

对 RSpec 使用以下测试:

RSpec.describe ApplicationHelper, :type => :helper do
  describe "#current_book" do
    book_1 = create(:book)

    params = {}
    params[:id] = book_1.id

    expect(helper.current_book).to eq(book_1)
  end
end

但由于某种原因,params[:id] 参数未正确传递。对此有什么建议吗?

【问题讨论】:

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


    【解决方案1】:

    你需要存根参数:

    RSpec.describe ApplicationHelper, type: :helper do
      describe "#current_book" do
        let(:first_book) { create(:book) }
    
        before(:all) { helper.stub!(:params).and_return(id: 1) }
    
        it "returns a book with a matching id" do
          expect(helper.current_book).to eq(first_book)
        end
      end
    end
    

    【讨论】:

    • 这条线应该放在哪里?
    • 我扩展了答案,希望对您有所帮助!
    • 请解释为什么需要存根。
    • 在给定的示例中,params 变量在块内声明,但它与在帮助程序实例中设置的 params 变量不同。因此,我们必须在我们正在测试的帮助程序实例上存根 params 变量
    • 出现错误:nil:NilClass 的未定义方法 `view_context'
    【解决方案2】:

    这里是另一种存根参数的方法。我认为这需要 rspec 3 无法确定。

    context 'path is a route method' do
      before { allow(helper).to receive(:params).and_return(order_by: { updated_at: :desc }) }
      subject { helper.sortable_link_to('Created At', order_by: :created_at) }
      it { is_expected.to match /comments/ }
      it { is_expected.to match /\?order_by/}
      it { is_expected.to match /\?order_by%5Bupdated_at%5D=asc/}
    end
    

    【讨论】:

      猜你喜欢
      • 2016-05-12
      • 2014-08-06
      • 1970-01-01
      • 2011-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-12
      • 1970-01-01
      相关资源
      最近更新 更多