代码之家  ›  专栏  ›  技术社区  ›  Carl Edwards monkbroc

在使用RSPEC和Rails 5+时,我应该使用什么来代替“分配”?

  •  0
  • Carl Edwards monkbroc  · 技术社区  · 6 年前

    我目前正在以请求规范的形式测试我的一个控制器的索引操作,并希望确保正在传递对象集合。到目前为止我已经咨询过了 post 指导意见:

    it "populates an array of contacts starting with the letter" do
      smith = FactoryBot.create(:contact, lastname: 'Smith')
      jones = FactoryBot.create(:contact, lastname: 'Jones')
      get :index, letter: 'S'
      expect(assigns(:contacts)).to match_array([smith])
    end
    

    不幸的是,上面的示例将引发此错误:

    NoMethodError: assigns has been extracted to a gem. To continue using it, add `gem 'rails-controller-testing'` to your Gemfile.
    

    我想知道在这种情况下,我会用什么来支持赋值?在这个新方法论的例子中,我一直在上上下下地寻找,但没有找到。

    1 回复  |  直到 6 年前
        1
  •  0
  •   max Mike Williams    6 年前

    it "returns an array of contacts starting with the letter" do
      smith = FactoryBot.create(:contact, lastname: 'Smith')
      jones = FactoryBot.create(:contact, lastname: 'Jones')
      get :index, letter: 'S'
      last_names = parsed_response["contacts"].map { |c| c["lastname"] }
      expect(last_names).to include 'Smith'
      expect(last_names).to_not include 'Jones'
    end
    

    let(:page) do
      Capybara::Node::Simple.new(response.body)
    end
    
    it "returns an array of contacts starting with the letter" do
      smith = FactoryBot.create(:contact, lastname: 'Smith')
      jones = FactoryBot.create(:contact, lastname: 'Jones')
      get :index, letter: 'S'
      expect(page).to have_content('Smith')
      expect(page).to_not have_content('Jones')
    end