ruby-on-rails - rails rspec -(第二次测试)预期响应为 < :redirect>, 但为 <200>

标签 ruby-on-rails ruby testing rspec controller

预期的响应是 <:redirect>,但是是 <200>

我的测试有:

describe "Link POST #create" do

  context "with valid attributes" do
    it "creates a new link" do
      expect{
        post :create, link: FactoryGirl.create(:link, :group => @group)
      }.to change(Link,:count).by(1)
    end

    it "redirects to the new link" do
      post :create, link: FactoryGirl.create(:link, :group => @group)
      # response.should redirect_to @link # Link.unscoped.last
      response.should redirect_to Link.unscoped.last # render_template :show
    end
  end

第一个测试通过,但第二个测试失败。

我的代码是:

  def create
    @link = Link.new(params[:link])

    respond_to do |format|
      if @link.save
        flash[:notice] = 'Link was successfully created.'
        format.html { redirect_to(@link) }
        format.xml  { render :xml => @link, :status => :created, :location => @link }
      else
        @selected_group = params[:group_id]
        format.html { render :action => "new" }
        format.xml  { render :xml => @link.errors, :status => :unprocessable_entity }
      end
    end
  end

我已尝试重定向和呈现,但无法通过第二个测试。

最佳答案

这里有一些应该让它工作的东西:

describe "Link POST #create" do

  context "with valid attributes" do

    def do_post( format = 'html' )
      attributes = FactoryGirl.build(:link).attributes.merge( :group_id => @group.id )
      post :create, :link => attributes, :format => 'html'
    end

    it "creates a new link" do
      expect{
        do_post
      }.to change(Link,:count).by(1)
    end

    it "redirects to the new link" do
      do_post
      response.should redirect_to( assigns[:link] )
    end
  end

第一个规范之所以有效,是因为您正在调用 FactoryGirl.create,因此从 Controller 中创建了一条记录,但很可能是 Controller 调用不起作用。

关于ruby-on-rails - rails rspec -(第二次测试)预期响应为 < :redirect>, 但为 <200>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10966193/

相关文章:

ruby-on-rails - Heroku 上的 Node.js : PostgreSQL on prod, SQLite3 on dev?

ruby-on-rails - 从枚举模型中设置 Rails 表单隐藏字段

Ruby:如何使用 .each 遍历数组?

ruby-on-rails - 无法在 Rails 4 中检索 attr_accessor

ruby - Ruby 循环 | Selenium |网络测试

ruby-on-rails - Ruby on Rails time_select 插件?

ruby-on-rails - 如何将 Ruby on Rails 应用程序转换为 Windows/Linux 服务?

ruby-on-rails - Capistrano & Bash : ignore command exit status

laravel - 从带有端点的数组生成 PHPUnit 测试

rest - 使用外部服务测试 Angular $resource