【问题标题】:Testing a Rails form_tag in Rspec在 Rspec 中测试 Rails form_tag
【发布时间】:2013-01-06 22:21:02
【问题描述】:

我无法在 Rspec 中模拟我的 form_tag。 form_tag 会将参数散列打包为简单散列,而 Rspec 将打包为带有参数的散列散列,在这种情况下,在 :session 散列内部,如:

{"session"=>{"email"=>"billy@example.com", "password"=>"foobar"}, "controller"=>"sessions", "action"=>"create" }

vs Rails form_tag:

{"utf8"=>"✓", "authenticity_token"=>"AiurjCANkzCJFl+oiJK2tQVzzxrET260bo1wxuDHB74=", "email"=>"billy@example.com", "password"=>"foobar", "commit" =>“登录”、“操作”=>“创建”、“控制器”=>“会话”}

会话控制器正在使用:

user = User.find_by_email(params[:email])

提取电子邮件参数。这将适用于开发,但对于我必须使用的 Rspec 测试:

user = User.find_by_email(params[:session][:email])

这是我最新的 Rspec 测试:

describe "success" do
before(:each) do
  @user = Factory(:user)
  @attr = {:email => @user.email, :password => @user.password }
end

it "should redirect to the user show page" do
  #post :create, :session =>   @attr #same results
  post sessions_path(:email => @user.email, :password => @user.password)
  response.should have_selector('h1', :content => @user.full_name)
end
end

由于上述参数散列的不同,这将失败。 Rspec 中有没有办法在单个哈希中向会话控制器发送参数以匹配 form_tag,如上所示?

【问题讨论】:

    标签: ruby-on-rails-3 rspec2


    【解决方案1】:

    您可以尝试在测试中手动传递参数

    describe "success" do
    before(:each) do
      @user = Factory(:user)
      @attr = {:email => @user.email, :password => @user.password }
    end
    
    it "should redirect to the user show page" do
      post :create, :email => @user.email, :password => @user.password
      response.should have_selector('h1', :content => @user.full_name)
    end
    end
    

    这会将参数发送到控制器中的方法

    {... "email"=>"billy@example.com", "password"=>"foobar" ...}

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-09
      • 1970-01-01
      • 1970-01-01
      • 2019-08-12
      相关资源
      最近更新 更多