【问题标题】:ArgumentError - wrong number of arguments (2 for 1) when testing show method of controllerArgumentError - 测试控制器的显示方法时参数数量错误(2 比 1)
【发布时间】:2019-03-19 05:50:54
【问题描述】:

我正在尝试为控制器的 show 方法编写测试。

方法如下:

def show
  if current_user
    goal= Goal.find_by_name(params[:id], :include => :projects, :conditions => ['projects.flag = true OR projects.user_id = ?', current_user.id])
  else
    goal= Goal.find_by_name(params[:id], :include => :projects, :conditions => ['projects.flag = true'])
  end

  @results = goal.projects if goal
end

这是我目前的测试:

describe '#show' do
  before :each do
    @user = FactoryGirl.create(:user)
    @project= FactoryGirl.create(:project, user: @user, flag: 1)
    @goal= FactoryGirl.create(:goal, name: 'goal')
    @goal_association= FactoryGirl.create(:goal_association, goal_id: @goal.id, project_id: @project.id)
    controller.stub(:current_user).and_return(@user)
  end

  it 'search by goal' do
    get :show, id: @goal.name

    expect(response.status).to eq 302
  end
end

此测试返回以下错误:

 Failure/Error: get :show, id: @goal.name
 ArgumentError:
   wrong number of arguments (2 for 1)

错误指向goal= Goal.find_by_name(params[:id], :include => :projects, :conditions => ['projects.flag = true OR projects.user_id = ?', current_user.id]) 行。

我不知道该怎么做。 任何有关这方面的线索都会有所帮助。

【问题讨论】:

  • 您使用的是什么 Rails 版本?您的 find_by_name 使用尝试建议 2.x。
  • 我正在使用 rails 版本 4.1.16 @MarekLipka 我不知道如何为这个方法编写测试。你能帮帮我吗?
  • 好吧,看看我的回答,应该可以的。而且我想您应该注意,您从 StackOverflow 复制的代码有多旧,因为很多答案都已过时。 :)
  • 它似乎无法识别scope。我可以改用Goal.find_by(name: params[:id]) 对吗? @MarekLipka
  • 我包括设置scope。但是,是的,你可以。

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


【解决方案1】:

您应该使用最新的语法,因为我假设您没有使用这个非常旧的 2.3 Rails 版本。我建议是这样的:

scope = if current_user
          Goal.joins(:projects).where('projects.flag = true OR projects.user_id = ?', current_user.id)
        else
          Goal.joins(:projects).where(projects: { flag: true })
        end
goal = scope.find_by(name: params[:id])

【讨论】:

    猜你喜欢
    • 2015-09-12
    • 1970-01-01
    • 2014-06-23
    • 2012-02-07
    • 2016-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多