Rspec测试搜索方法

时间:2017-08-29 18:30:33

标签: ruby-on-rails ruby rspec

TDD很新,我试图用Rspec测试搜索方法,但我一直在

expected: "Test project"
            got: #<ActiveRecord::Relation []>

projects_controller.rb

def index                                      
  @projects = Project.search(params) 
end 

project.rb

def self.search(params = {})
  return find_name(params[:search]) if params[:search].present?

  all
end

scope :find_name, ->(search) { where("name ILIKE :search", search: "%#{search}%") }

projects_spec.rb

require 'rails_helper'
RSpec.describe Project, type: :model do
it "finds a searched project by name" do
    FakeStubRequests.load
    project = create(:project, name: "Test project", database_url: "https://fake-database.firebaseio.com/", secret_key: "FakeSecretKey")
    @result = Project.search(search: project)
    expect(@result).to eq("Test project")
  end
end

1 个答案:

答案 0 :(得分:1)

您可能需要按Test project进行搜索并期望project,但反之亦然。但更好的是,搜索类似Test project的内容,例如roject

require 'rails_helper'

RSpec.describe Project, type: :model do
  it "finds a searched project by name" do
    FakeStubRequests.load
    project = create(:project, name: "Test project", database_url: "https://fake-database.firebaseio.com/", secret_key: "FakeSecretKey")
    @result = Project.search(search: "roject")
    expect(@result).to eq([project])
  end
end