为RSpec测试设置存在为true

时间:2013-05-28 08:58:10

标签: ruby-on-rails ruby testing rspec

我想为我正在测试的特定实例设置某些内容为“true”。它目前不存在,因此它的存在== false。

这是我到目前为止的代码。希望有人可以提供帮助。

invitations_controller中的

def join_request
  invitation_options = {recipient_id: current_user.id, project_id: @project.id, recipient_email: current_user.email}

  if ProjectInvitation.where(invitation_options).present?
    flash[:notice] = "You already sent a request to join this project."
    redirect_to :back
    return
  end
邀请函_controller_spec中的

describe "Send Join Request" do
  before do
    @invitation_options = {:recipient_id => @user.id, :project_id => @project.id, :recipient_email => 'address@gmail.com'}
    ProjectInvitation.where(@invitation_options).present? == true # This is what I'm stuck on. Pretty sure this doesn't work.
  end
  context "if you already sent a request" do
    it "should tell you that you already sent a request" do
      response.should have_text("You already sent a request to join this project.")
    end
    it "should redirect you to the previous page" do
      response.should redirect_to(:back)
    end
  end
end

3 个答案:

答案 0 :(得分:0)

考虑将此查询(ProjectInvitation.where(invitation_options).present?)提取到ProjectInvitation中的类方法,然后在测试中将其存根

答案 1 :(得分:0)

  

stub current_user方法。用工厂创建一个项目然后   只需使用属性{recipient_id创建ProjectInvitation:   current_user.id,project_id:@ project.id,recipient_email:   您的规范中的current_user.email}。

答案 2 :(得分:0)

您可以轻松地将'where'方法存根,但它会存储您对此模型的所有查询。例如:

Profile.stub(:where) { "555" }
Profile.where(:id => 5) #will return 555
Profile.where(:name => 'Phil') #will return 555

但最好的方法是使用FactoryGirl生成ProjectInvitation