Ruby on rails ArgumentError-测试控制器的show方法时参数数目错误(2对1)
我正在尝试为控制器的show方法编写测试 方法如下:Ruby on rails ArgumentError-测试控制器的show方法时参数数目错误(2对1),ruby-on-rails,rspec,controller,rspec-rails,Ruby On Rails,Rspec,Controller,Rspec Rails,我正在尝试为控制器的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[:i
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\u by\u name(参数[:id],:include=>:projects,:conditions=>['projects.flag=true或projects.user\u id=?',current\u user.id])
行
我不知道该怎么办。
任何与此相关的线索都会很有帮助。您应该使用最新的语法,因为我假设您没有使用这个非常旧的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])
您使用的Rails版本是什么?您的
find_by_name
使用尝试表明2.x。我正在使用rails版本4.1.16@MarekLipka,我不确定如何编写此方法的测试。你能帮我一下吗?好吧,看看我的答案,应该行得通。我想你应该注意,你从StackOverflow复制的代码有多旧,因为很多答案都过时了。:)它似乎没有识别范围
。我可以使用Goal.find_by(name:params[:id])
代替,对吗@MarekLipkaI包括设置范围
。但是是的,你可以。